Search code examples
linuxbashfile-listing

listing file is specific order linux


I would like to ask you for help with some script. I have files in one directory with one extension:

1_of_meany_files.ext
2_of_meany_files.ext
3_of_meany_key1_files.ext
5_of_meany_files.ext
6_key2_of_meany_files.ext

Now i'm trying build file.txt with list of these files but in specific order:

3_of_meany_key1_files.ext
6_key2_of_meany_files.ext
1_of_meany_files.ext
2_of_meany_files.ext
5_of_meany_files.ext

I would be appreciate for help. Thanks Marcin

==EDIT==

Hi, Thanks for your help. The scripts are working fine. However I have problem with one thing: If the key word has a digit inside it works perfect. But the key words can be without digits (S114 or S_114) then these scripts aren't works. What can I do with this? General I would like to sort files and put one on the top of the list with the key (S114 or S_114). So the files after sorting can looks like this:

Option One

    one_file_S114_text.ext
    rest_of_files_1.ext
    rest_of_files_2.ext
    rest_of_files_3.ext

Option Two

    one_file_S_114_text.ext
    rest_of_files_1.ext
    rest_of_files_2.ext
    rest_of_files_3.ext

In directory can be only one file with the key, but the key can be S114 or S_114

Thanks for your time regard Marcin


Solution

  • This is a bit tricky, because you want the files with no key in the end, so you can't just do print $2+0,$0 in the awk command. However, this awk-sort-cut pipeline should do what you want:

    $ printf "%s\n" * | awk -F'_key' '{print $2+0==0?1000000:$2+0,$0}'| sort -n | cut -d' ' -f 2-
    3_of_meany_key1_files.ext
    6_key2_of_meany_files.ext
    1_of_meany_files.ext
    2_of_meany_files.ext
    5_of_meany_files.ext