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/
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
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: $_" }'
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.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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: $_" }'
Alternatively the chomp could go outside of the if as well.
ASKER
Modified code to produce desired results.
ASKER
Here is what I get when running the command:
# ls | perl -ne 'if (/^(\d+-\d+)-(\d+)(_.+)$/)
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.