Reputation: 2833
I have a .txt file of pumpkinsizes that I'm trying to sort by size of pumpkin:
name |size
==========
Joe |5
Mary |10
Bill |2
Jill |1
Adam |20
Mar |5
Roe |10
Mir |3
Foo |9
Bar |12
Baz |0
Currently I'm having great difficulty in getting sort
to work properly. Can anyone help me sort my list by pumpkin size without modifying the list structure?
Upvotes: 1
Views: 126
Reputation: 106
The key point is the option -k
of sort
. You can use man sort
to see how it works. The solution for your problem follows:
sed -n '3,$p' YOUR_FILENAME| sort -hrt '|' -k 2
Upvotes: 3
Reputation: 246774
You can do this in the shell:
{ read; echo "$REPLY"; read; echo "$REPLY"; sort -t'|' -k2n; } < pumpkins.txt
That reads and prints the first 2 header lines, then sorts the rest.
Upvotes: 1
Reputation: 2259
You can simply remove the
name |size
==========
by using sed
command. Then whatever is left can be sorted using sort
command.
sed '1,2d' txt | sort -t "|" -k 2 -n
Here, sed '1,2d'
will remove the first 2 lines.
Then sort
will tokenize the data on character '|'
using option -t
.
Since you want to sort based on size which happens to be second token, so the token "size" can be specified by -k 2
option of sort
.
Finally, considering "size" as number, so this can be specified by option -n
of sort
.
Upvotes: 1
Reputation: 72639
The table headings need special consideration, since "sorting" them will move them to some random line. So we use a two step process:
a) output the table headings. b) sort the rest numerically (-n), reverse
order (-r), with field separator |
(-t), starting at field 2 (-k)
$ awk 'NR<=2' in; awk 'NR>2' in | sort -t '|' -nr -k 2
name |size
==========
Adam |20
Bar |12
Roe |10
Mary |10
Foo |9
Mar |5
Joe |5
Mir |3
Bill |2
Jill |1
Baz |0
Upvotes: 3