0

Anyone knows how to write a bash script that can rename all folders in a directory? It needs to delete the first words of all folders.

Currently it looks like this:

ABC DEF Folder1
ABC DEF Folder2
ABC DEF Folder3
...
ABC DEF Folder1000

Delete the identical letters

ABC DEF

To achieve

Folder1
Folder2
Folder3
...
Folder1000

I'm kinda new to linux and don't got a clue about bash scripting yet. Anyone who can provide hints/ solutions?

A real live preview

2 Answers2

2

Quick Answer

I'd not bother with script ... just rename

rename s/ABC\ DEF\ // *

s/string1/string2/ causes it to search & replace string1 with string 2.

string 1 is made longer due spaces and need to escape them '\ ', string 2 being empty '//'

finally * forces it to work on all files/dirs in current directory

Read the man rename and it'll provide clues. The main page refererences ' perlexprs' (perl expressions; meaning more man pages) but they are a superset of POSIX ones meaning you have more power, but can just limit yourself to posix too.

guiverc
  • 33,923
2

For simple text matches such as this (which don't really require the power of regular expressions) there's also mmv e.g. given

$ ls -d */
ABC DEF Folder1/   ABC DEF Folder3/  ABC DEF Folder6/  ABC DEF Folder9/
ABC DEF Folder10/  ABC DEF Folder4/  ABC DEF Folder7/
ABC DEF Folder2/   ABC DEF Folder5/  ABC DEF Folder8/

then

mmv -r 'ABC DEF *' '#1'

results in

$ ls -d */
Folder1/   Folder2/  Folder4/  Folder6/  Folder8/
Folder10/  Folder3/  Folder5/  Folder7/  Folder9/

FWIW it's not actually much more work to script it in the (bash, or POSIX sh) shell -

for f in */; do mv -- "$f" "${f#ABC DEF }"; done
steeldriver
  • 143,099