6

I have below files in unix, I want to sort the files based on date & time in the file names

ABC_XYZ.20170201.223147.txt
ABC_XYZ.20170201.223146.txt
ABC_XYZ.20170127.223141.txt
ABC_XYZ.20170125.223139.txt
ABC_XYZ.20170214.223134.txt

I am expecting below as output

ABC_XYZ.20170125.223139.txt
ABC_XYZ.20170127.223141.txt
ABC_XYZ.20170201.223146.txt
ABC_XYZ.20170201.223147.txt
ABC_XYZ.20170214.223134.txt

I tried using sort -k and sort -n, maybe I am not using them in the right way.

1
  • 6
    sort alone works on that sample. sort -t . -k 2 to sort on the part of the line after the first . Mar 9, 2017 at 20:54

1 Answer 1

3

If all the files in the current folder have the same format as described, you could use the following:

ls | sort -t . -k 2 

The -t switch sets the delimiter as a .
The -k switch indicates which key to use for the sort.

With the filename format you have supplied, you don't need the -n switch as the number of digits is the same within each filename. If this is not always the case, you can easily add the -n switch, too:

ls | sort -n -t . -k 2 

Again, if there are varying lengths of digits for each section of the filenames, you may want to specify both keys and how far to extend them:

ls | sort -n -t . -k 2,2 -k 3,3
1
  • Great, that's awesome!
    – MikeD
    Mar 12, 2017 at 17:38

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .