hsayya
hsayya

Reputation: 131

Sorting filenames by numeric fields (substrings)

I have a set of files in a folder A1, with the following naming convention :

MCU1_0001_01 
MCU2_0002_01 
MCU1_0001_02 
MCU2_0002_02
MCU1_0003_01
MCU2_0003_02

The 4 digit value in the middle continues to increment until the value of 34, whereas the value that follows after MCU alternates between 1 and 2 and so does the last two digits at the end of the string.

That being said, I wanted to sort these files according to the middle value first, then the value at the end of the string, second. Note, I also am not interested in sorting the value that follows "MCU".

How can I do that?

this is what i've been trying

ls MCU[12]_00[0-9][0-9]_0[12] sort -t 

Upvotes: 0

Views: 50

Answers (1)

randomir
randomir

Reputation: 18697

Split fields on _ and sort by fields 2 to 3:

$ ls | sort -t_ -k2,3
MCU1_0001_01
MCU1_0001_02
MCU2_0002_01
MCU2_0002_02
MCU1_0003_01
MCU2_0003_02

See man sort for description of -t/--field-separator=SEP and -k/--key=KEYDEF.


If your fields are not zero-padded, you want to use -n for numeric sort:

sort -t_ -k2n -k3n

(this sorts by numeric value of second field, and then by numeric value of third field). To debug how sort interprets fields, run with --debug flag.

Upvotes: 1

Related Questions