List numerically in ascending order

Hello,
I am running ubuntu 16.04 and trying to list all files inside a directory, I need to sort them in ascending order. While surfing on the site, I found an old thread but somehow it did not work.
Link

Ascending order with sort -nk2 myfile.txt command gives below output:

file media_w1956306127_b2500000_0.ts
file media_w1956306127_b2500000_100.ts
file media_w1956306127_b2500000_101.ts
file media_w1956306127_b2500000_102.ts
..
..
file media_w1956306127_b2500000_10.ts
file media_w1956306127_b2500000_110.ts
file media_w1956306127_b2500000_111.ts
..
..
file media_w1956306127_b2500000_699.ts

Other method is a bit longer to do that. ( Rename prefix media_w1956306127_b2500000_ in each filename , then, print the file names with for loop, variable from 0 to 699)

Could you please let me know how I may sort it as expected? Maybe sort command takes all strings as alphabet so it does not take into account the value of the string so that listing in ascending order does not give what I expected to get.

Thank you
Boris

Hi, try

sort -t_ -k1,3 -k4n
1 Like

Not sure I correctly understand your request. Are we talking of sorting a file, or a directory listing? Did you check for the links at the bottom of this page? Given "media_w1956306127_b2500000" is and stays constant in your data, how far would

sort -t"_" -nk4 file
..
..
..
..
file media_w1956306127_b2500000_0.ts
file media_w1956306127_b2500000_10.ts
file media_w1956306127_b2500000_100.ts
file media_w1956306127_b2500000_101.ts
file media_w1956306127_b2500000_102.ts
file media_w1956306127_b2500000_110.ts
file media_w1956306127_b2500000_111.ts
file media_w1956306127_b2500000_699.ts

get you?

1 Like

Thank you Dear Scrutinizer and Dear Rudic,
Your commands work good. Thank you again.
The text file includes all files inside the directory.
I do not understand why we need to specify underscore as limiter in column2. Normally each line is space seperated.
Thank you so much for your return.

Kind regards
Boris

That how we "isolate" the relevant numerical (!) sort field from the rest of fields that are considered strings. We're lucky here in that sort seems to disregard the .ts extension when extracting / calculating the numerical field.

1 Like

Hi
You can use the -V option

sort -V

or even sort right away in a file

vim -nes +'%!sort -V' +wq file
2 Likes

Another option would be at the time of listing

ls -1v *media*

mannu25251@debian8.9:~/dir$ ls -1v *media\*
    media_w1956306127_b2500000_0.ts
    media_w1956306127_b2500000_10.ts
    media_w1956306127_b2500000_100.ts
    media_w1956306127_b2500000_101.ts
    media_w1956306127_b2500000_102.ts
    media_w1956306127_b2500000_109.ts
    media_w1956306127_b2500000_110.ts
    media_w1956306127_b2500000_111.ts
    media_w1956306127_b2500000_699.t
    media_w1956306127_b2500000_699.ts
    media_w1956306127_b2500000_1112.ts
2 Likes