0

I want to sort my file by decreasing number of the second column, but not changing the place of the header. Currently it is like this in a csv file that has two columns like this:

Person     Age

Sarah      15

Robert     23

Emma       31

Bob        9

I want it to be like this:

Person     Age

Emma       31

Robert     23

Sarah      15

Bob        9

Please help a beginner in Unix.

0

3 Answers 3

1

Read http://man7.org/linux/man-pages/man1/sort.1.html to learn about the sort command on UNIX/Linux. That's how I and everyone else learned.

$ sort --key 2 --reverse --numeric-sort myfile > mysortedfile

The only problem is that this sorts the line with "Person Age" as if it had the numeric value of zero, and moves it to the last line of the file. You then have to move that line after sorting the file.

Sign up to request clarification or add additional context in comments.

Comments

0

To solve the "header in front" problem as outlined in Bills answer, you could use awk in addition to sort:

awk 'NR==1 {print ; next } { print | "sort -n -r -k2"  }' yourfile > sorted_file
  • the condition NR==1 applies only for the first line: it is printed
  • all other line are piped to the sort command (you could do the sorting in awk itself, but that would be a bit longer )

Comments

0

This will do the trick except remove blank lines:

sed -n '1 ! p' in.txt | sort --key 2 --reverse --numeric-sort | sed '1 i\Person\tAge' > out.txt

3 Comments

thanks, they come in the front, but they are not separated in different cells in csv. How to fix it?
I'm sorry, I don't understand your question.

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.