0

I have following files in a directory:

trunk_rev.94564.zip
trunk_rev.94565.zip
trunk_rev.94566.zip
trunk_rev.94567.zip
trunk_rev.94568.zip
trunk_rev.94569.zip
v15_rev.94560.zip
v15_rev.94561.zip
v15_rev.94562.zip
v15_rev.94563.zip
v15_rev.94564.zip

How could I get a list of N (e.g. 3) newest by ctime files for each pattern ? Filenames could be different. E.g.:

trunk_rev.94567.zip
trunk_rev.94568.zip
trunk_rev.94569.zip
v15_rev.94562.zip
v15_rev.94563.zip
v15_rev.94564.zip
<some_another_file>.zip
<some_another_file>.zip
<some_another_file>.zip

Thanks in advance!

3
  • 1
    Welcome on SuperUser. What have you tried so far to accomplish your goal? Which problem did you face? My first thought is to do a little bash script... but beware that it is in general dangerous (and deprecated) to parse the output of ls, mainly because the unforeseen presence of space or special characters (newline, tab...) in the filename. Please edit your question with your attempt and problem. – Hastur Mar 31 '16 at 17:28
  • Are you asking people here to do your homework or something? – user127350 Mar 31 '16 at 22:48
  • @Radoo, nice sarcasm – johny_amamam Apr 1 '16 at 10:38
0

Give this a try:

ls -1rt | awk 'BEGIN { FS="."; OFS="."; } { if (count[$1]<3) { count[$1]++; filenames[i++]=$0; } } END { for ( i in filenames ) { printf("%s\n",filenames[i]); } }'

The files will be listed by ctime order only.

To list them by ctime grouped by name, add a sort command:

ls -1rt | awk 'BEGIN { FS="."; OFS="."; } { if (count[$1]<3) { count[$1]++; filenames[i++]=$0; } } END { for ( i in filenames ) { printf("%s\n",filenames[i]); } }' | sort -t . -k 1,1
1
  • Warning: This will work only if in the filename are not present special character as the newline one. You can paste the newline for example renaming a pdf file from the title of the document written inside... So use it with wisdom. It can be harmful to parse the output of ls mainly because the presence of special characters in the filename. It's easy to do a fast script that works today and think tomorrow that it is solid and generally valid... Moreover what will happen if you have v15_rev.bis.01..09 and v15_rev.01? – Hastur Apr 10 '16 at 8:38
2

You should read the manual of ls at this point:

-c with -lt: sort by, and show, ctime (time of last modification of file status information) with -l: show ctime and sort by name other-wise: sort by ctime, newest first

and the manual of head, if you are not familiar with it yet.

0
1

Try the following:

ls -l --time-style=full-iso | sort -k6 | tail -n3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.