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

  • why use a script? why not just rename (with globbing) – guiverc Jan 23 '18 at 23:24
  • Because that's a shit tons of work for a huge amount of folders and I know a smarter solution is possible. I want to save some of the chars to be able to identify the folders by their name. – Sir hennihau Jan 23 '18 at 23:25
  • rename s/ABC\ DEF\ // * isn't a lot a work – guiverc Jan 23 '18 at 23:30
  • krename is a useful gui tool here, particularly if you have KDE. – pbhj Jan 24 '18 at 4:19
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.

|improve this answer|||||
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
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.