How to batch-rename files by date? How to batch-rename files by date? unix unix

How to batch-rename files by date?


You can use the rename command:

rename 's/^file\.([0-9]{4})-([0-9]{2})-([0-9]{2})\.txt$/file_y$1m$2d$3.txt/' *

This uses Perl regular expression substitution to transform filenames. The command above says:

  1. Find files starting ^ with file. (the . has to be escaped, otherwise it matches any character), followed by the captured () group [0-9]{4} (a digit, 4 times), then -, then another captured group of a digit twice, etc., and ending $ with .txt;

  2. Then, rename those files to file_y followed by the first captured group $1, followed by m, followed by the second captured group $2, etc., and ending with .txt.

You should also be able to work out how to use the same command to solve your second problem, with what you no know about how rename works.


You can also use sed:

for example:

ls | while read f; do echo "mv $f $(echo $f | sed 's/\./_y/;s/-/m/;s/-/d/')"; done

This will show you the commands that bash will run. To actually do the move, remove the echo and quotes:

ls | while read f; do mv $f $(echo $f | sed 's/\./_y/;s/-/m/;s/-/d/'); done