Sunday, April 10, 2022

[SOLVED] Renaming directories

Issue

I've got like 230 directories of this kind (1367018589_name_nameb_namec_named) and would like to rename them into (Name Nameb Namec Named).

To be more precise:

  1. Removing numbers
  2. Replacing underscores with spaces (except the first understore which comes after the numbers)
  3. First letter into capital letter

a easy one-liner is preferred since I'm quite a newbie regarding Linux and bash. Bash script wouldn't be a problem either - just a small explanation how to use it would be very much appreciated. Meaning that I can understand once I know the command, but having troubles coming up with in my own.

Much thanks in andvance


Solution

In one line (updated to capitalize first letter of each word -- missed that the first time):

$ for f in * ; do g=$(echo $f | sed s/[0-9_]*// | sed s/_/\ /g | sed "s/\b\(.\)/\u\1g") ; echo "mv \"$f\" to \"$g\"" ; done

Once you are happy that it is going to do what you want change

echo "mv \"$f\" to \"$g\""

to

mv -i "$f" "$g"

Note, the -i option is to avoid the case of accidentally overwriting a file (say if you had files 123_test and 345_test for instance)



Answered By - Wayne Vosberg
Answer Checked By - Dawn Plyler (WPSolving Volunteer)