Bash – list file names with sorted order – ls command

bashlsshellsortingunix

I have some files in a UNIX directory:

/opt/apps/testloc $ ls -mn 
test_1.txt
test_2.txt
test_11.txt
test_12.txt
test_3.txt

I want to list this with ls command and I need the output in sorted order based on the numbers at the end of the file name. Say output should be like below.

test_1.txt, test_2.txt, test_3.txt, test_11.txt, test_12.txt

I am not able to get as mentioned. These file names were considered as text and they were sorted as below,

test_11.txt, test_12.txt, test_1.txt, test_2.txt, test_3.txt

My command ls –mn (I need the output to be in comma separated format so I have used -m)

I need this to be done to process the files in incremental format in my next process.

Best Answer

If you version of sort can do a version sort with -V then:

$ ls | sort -V | awk '{str=str$0", "}END{sub(/, $/,"",str);print str}'
test_1.txt, test_2.txt, test_3.txt, test_11.txt, test_12.txt

If not do:

$ ls | sort -t_ -nk2,2 | awk '{str=str$0","}END{sub(/,$/,"",str);print str}'
test_1.txt, test_2.txt, test_3.txt, test_11.txt, test_12.txt