Rename files using sed and mv Rename files using sed and mv bash bash

Rename files using sed and mv


You can try this script in bash:

for filename in *.jpg; do  newFilename=$(sed -E 's#img_([0-9]{1,2})-([0-9]{1,2})-([0-9]{1,2})_(.*)$#newyears_20\3-\2-\1_\4#' <<< "$filename")  mv "$filename" "$newFilename"done

sed -E is supported by gnu sed also.


Without a for loop.

ls | grep 'jpg$' | sed '#Save the original filenameh#Do the replacements/img_\(.*\)-\(.*\)-\(.*\)_\([0-9][0-9]\)\./newyears_20\3-\1-\2_0\4.//s/img_\(.*\)-\(.*\)-\(.*\)_\([0-9][0-9][0-9]\)/newyears_20\3-\1-\2_\4//#Bring the original filename backxGs/^\(.*\)\n\(.*\)$/mv "\1" "\2"' | bash

Ommit piping to bash to see the results before mv

Thanks to http://www.gnu.org/software/sed/manual/sed.html#Rename-files-to-lower-case


I remember messing around with this sort of thing. I found it often useful to create a script that you execute to do what you want:

ie. output of your script would be a file like:

mv   file1 file2mv   file3 file4.....mv   fileN fileM

To create this, just do a ls | grep date pattern | sed script to stick mv file1 to file2 > myscript

then just execute ./myscript

This way you have a better look at the intermediate output to figure out what's going wrong.