Reputation: 23
What commands could I use to rename a few hundred files that are currently named
file.2003-01-02.txt
file.2003-01-04.txt
... and so on? I would like them to be named:
file_y2003m01d02.txt
file_y2003m01d04.txt
... etc.
In other words, file.2007-12-09.txt
would become file_y2007m12d09
. Is there a simple set of commands to do this?
Similarly I have another problem, where files are named file_y2003m02d01_grid.txt
. I would like to know how to remove _grid
from each filename, so that it matches the format I proposed above.
Upvotes: 2
Views: 1014
Reputation: 9946
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
Upvotes: 0
Reputation: 59118
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:
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
;
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.
Upvotes: 3