0

I am trying to rename a folder with files which contain a datestamp like this:

string_DD-MM-YYYY_hhmm.pdf

to this format:

string_YYYY-MM-DD_hhmm.pdf

so that they sort by date when sorted by filename.

Example: PB_KAZ_KtoNr_0463266665_01-02-2014_0341.pdf should become PB_KAZ_KtoNr_0463266665_2014-02-01_0341.pdf.

I found this similar question but it's regarding DDMMYYYY format instead of DD-MM-YYYY and the answeres are way to complicated for my situation. As the string always is the same in content and length (24 characters) a simple command, that splits and reassembles the string by positions would be sufficient.

Thanks in advance!

Anton S.
  • 123
  • 2
    when you hint that "a simple command [....] would be sufficient", it is hard to image that you cannot get enough information to apply yourself reading man sed(1) or man awk(1). did you consult the manual? – humanityANDpeace Jan 07 '17 at 12:54
  • @humanityANDpeace thanks for pushing me in the right direction. As i'm new to this, i didn't know where o start. – Anton S. Jan 07 '17 at 14:37

2 Answers2

3

With Perl‘s rename (standalone command):

rename -n 's/(.*)_(.*)-(.*)-(.*)_(.*.pdf)/$1_$4-$3-$2_$5/' *.pdf

If everything looks fine remove -n.

Cyrus
  • 12,309
0

This is a crude method, especially if there are a lot of files, but most basic one with awk:

It assumes you don't have any other pdf in folder, except string_DD-MM-YYYY_hhmm.pdf ones, and that string_ part is 24 characters long

cd to folder and then run this:

for i in *.pdf; do mv $i `\ls -1 $i | awk '{print substr ($0, 0, 24)}'``\ls -1 $i | awk -F[_.] '{print$(NF-1)}'| awk -F- '{print$3"-"$2"-"$1}'`.pdf; done
ralz
  • 1,996
  • 13
  • 17
  • thanks! This would be exactly, what i asked for. But for some reason the datepart gets stripped completely, when i run this command. I'm now using the answer from Cyrus and Sundeep, as it is a bit more flexible. Thanks anyway! – Anton S. Jan 07 '17 at 15:15