Sort files according to the name containing numeric values

I have files in my system like this -

-rw-r--r-- 1 abc abcadm 14852497 Jul 23 01:11 ABCD_72_3_20210722_163502.csv
-rw-r--r-- 1 abc abcadm 14853145 Jul 23 01:11 ABCD_72_1_20210722_163502.csv
-rw-r--r-- 1 abc abcadm 14839699 Jul 23 01:11 ABCD_72_2_20210722_163502.csv
-rw-r--r-- 1 abc abcadm 14842673 Jul 23 01:11 ABCD_72_5_20210722_163502.csv
-rw-r--r-- 1 abc abcadm 14843811 Jul 23 01:11 ABCD_72_4_20210722_163502.csv

I want to sort those files to print only file name and with sorted manner like below:

ABCD_72_1_20210722_163502.csv
ABCD_72_2_20210722_163502.csv
ABCD_72_3_20210722_163502.csv
ABCD_72_4_20210722_163502.csv
ABCD_72_5_20210722_163502.csv

I am using the below to command to sort it in ascending order and to print just name but the list is not getting sorted.

ls -l | ABCD_72_[0-9]*_20210722_163502* | awk '{print $9}' | sort

Please suggest me where I am wrong or any alternative of this?

0

3 Answers

First, don't parse the output of ls. We can modify the answer to a different question a bit to make it non-recursive, and then find ./ -maxdepth 1 -printf "%f\n", and you want it sorted, so pipe it into sort. The final command is

$ find ./ -maxdepth 1 -printf "%f\n" | sort

As pointed out by @Rinzwind, if you want to numerically sort (so 2 could come before 12), add --numeric-sort to the end of the command making it.

find ./ -maxdepth 1 -printf "%f\n" | sort --numeric-sort
2

Have you considered simply

ls -v -1

This can also be employed naturally with a file specification such as:

ls -v -1 ABCD*

or

ls -v -1 A*.csv

If you switch to zsh, you can use its numeric glob qualifier:

 n sets the NUMERIC_GLOB_SORT option for the current pattern

(see Glob Qualifiers under the FILENAME GENERATION section of man zshexpn).

Ex.

 % print -rC1 ABCD_*.csv(n)
ABCD_72_1_20210722_163502.csv
ABCD_72_2_20210722_163502.csv
ABCD_72_3_20210722_163502.csv
ABCD_72_4_20210722_163502.csv
ABCD_72_5_20210722_163502.csv

or (in reverse numeric order)

 % print -rC1 ABCD_*.csv(nOn)
ABCD_72_5_20210722_163502.csv
ABCD_72_4_20210722_163502.csv
ABCD_72_3_20210722_163502.csv
ABCD_72_2_20210722_163502.csv
ABCD_72_1_20210722_163502.csv
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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

You Might Also Like