Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename files using sed and mv

Tags:

regex

bash

sed

mv

I want to rename files in the format:

img_MM-DD-YY_XX.jpg

img_MM-DD-YY_XXX.jpg

to:

newyears_YYYY-MM-DD_XXX.jpg

Where:

  • YYYY = year
  • MM = month
  • DD = day
  • XXX or XX = photo number

I came up with this script but it isn't working:

for filename in ?*.jpg; do
        newFilename=$(echo $filename | \
        sed 's/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/' -)
        mv $filename $newFilename
done

Any help would be greatly appreciated.

like image 610
tiagob Avatar asked Apr 15 '11 02:04

tiagob


1 Answers

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.

like image 128
anubhava Avatar answered Oct 16 '22 13:10

anubhava