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!

2
  • 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? Commented Jan 7, 2017 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. Commented Jan 7, 2017 at 14:37

2 Answers 2

3

With Perl‘s rename (standalone command):

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

If everything looks fine remove -n.

4
  • can use s/(\d{2})-(\d{2})-(\d{4})/$3-$2-$1/ to be specific to date format... Commented Jan 7, 2017 at 13:37
  • I think you should specify that rename exists in different forms in different distributions. I found useful this. Commented Jan 7, 2017 at 15:12
  • works like a charm in Ubuntu 16.04! Thanks a lot! Commented Jan 7, 2017 at 15:17
  • @andreatsh: Thank you for this link. Anton, you are welcome. Commented Jan 7, 2017 at 15:24
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 
1
  • 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! Commented Jan 7, 2017 at 15:15

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.