Search code examples
bashsortingls

How to sort by specific 'field' in filename


I have files in a folder where the filenames are of the form:

2352_GF_somerandomstring.txt, i.e. someNumber_twoletters_somestring.

using flags on ls the best I can achieve is to sort by different criteria similarly for sort.

What I'd like is to have the list sorted by the 'twoletters'. I.e. ignore the prefix-number and sort by the 'GF'-portion (in the sample), but still show me the complete file names (i.e. including the prefix-number).

The closest I got is (without writing a complete script): ls | cut -d '_' -f2- |sort

but the cut part removes everything in front, which I still need to see.

Any ideas on how to do this in a simple way? (Hopefully a oneliner).


Solution

  • like this: ls | sort -t '_' -k 2

    -t is separator and -k is column