-1

I have question about sorting files,and my question is different from other questions about sorting I have a folder including hundereds of files looks like this

anacovaux_1052_summary_betai.out
anacovaux_1052_summary_Pdelta.out
anacovaux_1052_summary_pij.out
anacovaux_1053_DIC.out
anacovaux_1053_summary_betai.out
anacovaux_1053_summary_beta_params.out
anacovaux_1048_DIC.out
anacovaux_1048_summary_betai.out
anacovaux_1043_summary_pi_xtx.out
anacovaux_1058_DIC.out

I wanted to know is there any way that I could sort them numerically? I mean get something like this:

anacovaux_1043_summary_pi_xtx.out
anacovaux_1048_DIC.out
anacovaux_1048_summary_betai.out
anacovaux_1052_summary_betai.out
anacovaux_1052_summary_Pdelta.out
anacovaux_1052_summary_pij.out
anacovaux_1053_DIC.out
anacovaux_1053_summary_betai.out
anacovaux_1053_summary_beta_params.out
anacovaux_1058_DIC.out
Anna1364
  • 1,026

2 Answers2

3

Using ls from GNU coreutils (default on most Linux systems):

$ ls -v -1

This will list the filenames in one single column (-1), sorted using the natural sort order for numbers within the filename ("version sorting", -v). This assumes that all filenames have the same prefix string up to the actual number (anacovaux_ for example).

For systems without GNU ls:

$ print '%s\n' * | sort -t '_' -k2,2n

This will sort the names on the number after the first _ character in the name. Again, it assumes that the filename prefix is constant (this solution totally ignores the prefix up to the first _).

Kusalananda
  • 333,661
2

If you want to list files in a folder in custom sort order:

ls -1 yourfolder | sort -t'_' -k2,2n
  • 2
    What the OP wrote is actually irrelevant in this case... Again, -1 is not needed here because ls by default prints one entry per line with a few exceptions ("output is a terminal" being one of them). Does any of the mods know why has my previous comment vanished ? – don_crissti Aug 29 '17 at 20:52
  • @don_crissti, I don't see a critical problem here with using -1 option to adjust the output (print only filenames) – RomanPerekhrest Aug 29 '17 at 21:00
  • thank you.@RomanPerekhrest it does the job partially for me. I have some files like anacovaux_105_DIC.out. So when I use your code it comes after anacovaux_1048_summary_betai.out....Is there any solution for that? Indeed my file are from 1-2181. I just presented a few of them as an example – Anna1364 Aug 29 '17 at 21:46
  • @Anna1364, just add n (natural sorting) flag to sort command. I couldn't give you this answer fast (6 ours ago) cause we are in different time zones – RomanPerekhrest Aug 30 '17 at 04:44