Link to home
Start Free TrialLog in
Avatar of bdhtechnology
bdhtechnology

asked on

Linux rename files by reordering dates in the file name

I have a ton of files and folders that are named in the format: MM-DD-YY_filename that I want to rename to YYYY-MM-DD_filename  Is the a oneeliner that would work to rename all the files/folders in a particular directory?  All the files/folders are in one folder so it wouldn't need to be recursive.  Here is an example of the old file name (left side) and what the new file name should look like (right side).

01-13-14_reg_min.htm   =>  2014-01-13__reg_min.htm
01-14-08_cc_agd.htm     =>  2008-01-14_cc_agd.htm
01-14-08_cc_agd_files/   =>  2008-01-14_cc_agd_files/
SOLUTION
Avatar of wilcoxon
wilcoxon
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of bdhtechnology
bdhtechnology

ASKER

Yes all are from 2000 or later.

Here is what I get when running the command:

# ls | perl -ne 'if (/^(\d+-\d+)-(\d+)(_.+)$/) { my $yr = '19' . $2; rename $_, "$yr-$1$3" or die "could not rename $_ to $yr-$1$3: $!" } else { warn "invalid filename: $_" }'
could not rename 01-08-07_cc_agd.docx
 to 1907-01-08_cc_agd.docx: No such file or directory at -e line 1, <> line 1.
I think the problem may be the new line at the end:
# ls -1 | perl -ne 'if(/^(\d+-\d+)-(\d+)(_.+)$/) { rename("$_", "20$2-$1$3") or die "could not rename \"$_\" to \"20$2-$1$3\": $!" } else { warn "invalid filename: $_" }'

Open in new window

Produces:
could not rename "01-08-07_cc_agd.docx
" to "2007-01-08_cc_agd.docx": No such file or directory at -e line 1, <> line 1.

Open in new window

ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Glad you were able to work it out.  My code should work if you add chomp as the first thing within the if block (as you said, it looks like there's a newline at the end of the filename).

ls | perl -ne 'if (/^(\d+-\d+)-(\d+)(_.+)$/) { chomp; my $yr = '19' . $2; rename $_, "$yr-$1$3" or die "could not rename $_ to $yr-$1$3: $!" } else { warn "invalid filename: $_" }'

Open in new window

Alternatively the chomp could go outside of the if as well.
Modified code to produce desired results.