regexbashsedmv

Rename files using sed and 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.


Solution

  • 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.