I have a bunch of files like FileNameX.cpp and I would like to rename all of them to their respective file_name_x.cpp.

  • does this answer work for you? – numand Nov 2 '16 at 19:32

This bash command do the job. From the command line, enter the folder, and run this line:

for file in ./* ; do mv "$file" "$(echo $file|sed -e 's/\([A-Z]\)/_\L\1/g' -e 's/^.\/_//')" ; done

In script form it looks like this:

for file in ./* ; do
    mv "$file" "$(echo $file|sed -e 's/\([A-Z]\)/_\L\1/g' -e 's/^.\/_//')"

Basically sed is used to manipulate strings. There're two expressions:

  1. s/\([A-Z]\)/_\L\1/g: searches for capitals to substitutes them for lower case and add the underscore

  2. s/^.\/_//: removes any underscore which was inserted due to the first letter being a capital (i.e. you don't want _file_name_x.cpp.

Consider using -v, --verbose on mv to explain what is being done.

  • There's a single quote missing after the first -e – Dominic Bartl Jan 24 '18 at 11:33

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.