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?


Solution 1:

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