Laura
Laura

Reputation: 360

Linux - Sort based on 2 fields names

I have several txt files "file_i.txt" that look like this:

id, size, price, colour 
1, 2, 10, black
2, 8, 5, blue
...

All the files contain those fields, but the fields order may be different.

I would like to sort every file based on two features, price first and then size. I know it is possible to use the command sort to sort on two fields in this way:

sort -k2,3 -k1,2 file_i.txt

However, as the field position is different in every file, is there a way to sort based on the field name instead?

Thanks

Upvotes: 3

Views: 1069

Answers (3)

hek2mgl
hek2mgl

Reputation: 158020

Basically the sort command should look like this:

sort -k3n -k2n input

where N in -kN is the number of the key, and n means sort numeric.

sort can't sort by field names. You need to get the column number somehow. I'm using awk for that:

kprice=$(awk -F', ' -vfield=price 'NR==1{for(i=1;i<=NF;i++){if($i==field){print i;exit}}}' a.txt)
ksize=$(awk -F', ' -vfield=size 'NR==1{for(i=1;i<=NF;i++){if($i==field){print i;exit}}}' a.txt)

sort -k"$kprice"n -k"$ksize"n a.txt

Upvotes: 1

Slizzered
Slizzered

Reputation: 899

you could do some preprocessing:

for each file:

  • transpose file
  • sort on first column (the names)
  • revert the transposition

Then, all columns will be ordered the same way and you can use your standard sort approach.


Transposing a file in bash is already solved in other questions here on SO:

Upvotes: 0

Luca Davanzo
Luca Davanzo

Reputation: 21520

I think you have to write a script by yourself, say "mySort" and launch as:

./mySort "id" "size"

Pseudocode, assuming that the first line of file contains "column" name:

read input list
for each element in list, save the position (parsing first line)
apply sort

Upvotes: 0

Related Questions