Jose Ricardo Bustos M.
Jose Ricardo Bustos M.

Reputation: 8164

How sort specific column in bash (linux) without modifying other columns and without creating a temporary file?

Input file

0 1.0069770730517629 A
1 1.0068122761874614 A
2 1.0004297763706849 B  
3 1.0069220626905635 C
4 1.0079998216945956 C
5 1.0006092898635817 D
6 1.0071274842017928 A
7 1.0083750686808803 A
8 1.0006868227863552 B  
9 1.0073693844413083 C  
10 1.0086546525825624 C
11 1.0007234442925264 D

Expected output:

0 1.0086546525825624 A
1 1.0083750686808803 A
2 1.0079998216945956 B
3 1.0073693844413083 C
4 1.0071274842017928 C
5 1.0069770730517629 D
6 1.0069220626905635 A
7 1.0068122761874614 A
8 1.0007234442925264 B
9 1.0006868227863552 C
10 1.0006092898635817 C
11 1.0004297763706849 D

My solution using a temporal file

awk '{print $2}' input.txt | sort -gr > temp.txt
paste input.txt temp.txt | awk '{print $1,$4,$3}'
rm temp.txt

Question

Is posible sort a specific column in bash (linux) without modifying other columns and without creating a temporary file?

Upvotes: 1

Views: 143

Answers (2)

karakfa
karakfa

Reputation: 67467

awk to the rescue

awk '{c1[NR]=$1; c2[NR]=$2; c3[NR]=$3} END {asort(c2); for(i=1;i<=NR;i++) print c1[i],c2[NR+1-i],c3[i]}'

Upvotes: 1

Barmar
Barmar

Reputation: 780871

You can use - as a filename argument to paste to tell it to use standard input.

cut -d' ' -f2 input.txt | sort -gr | paste input.txt - | cut -d' ' -f1,4,3

And if it didn't support this, you could use process substitution.

paste input.txt <(cut -d' ' -f2 input.txt | sort -gr) | cut -d' ' -f1,4,3

Upvotes: 2

Related Questions