1

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?

4 Answers 4

3

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
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

1

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.

2 Comments

This sorts ascending, not descending.
@Jens: Since OP did not mentioned the sort order, so kept it as default ascending order. However -r (reverse or descending) option can be provided in sort command.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.