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.
Asked
Active
Viewed 7,998 times
1 Answers
17
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:
#!/bin/bash
for file in ./* ; do
mv "$file" "$(echo $file|sed -e 's/\([A-Z]\)/_\L\1/g' -e 's/^.\/_//')"
done
Basically sed is used to manipulate strings. There're two expressions:
s/\([A-Z]\)/_\L\1/g: searches for capitals to substitutes them for lower case and add the underscores/^.\/_//: 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.
Hadog
- 696
- 1
- 8
- 19