Shell – Sort a file based on the middle part

filenamesshell-scriptsort

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.

Best Answer

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
Related Question