简体   繁体   中英

How to sort file using grep, sort in LINUX

I have a file that starts off like this:

#Population,    Year,   County
3900,   1969,   Beaver
3798,   1970,   Beaver
3830,   1971,   Beaver
3864,   1972,   Beaver
3993,   1973,   Beaver
3976,   1974,   Beaver
4064,   1975,   Beaver

And I need to be able to sort through this file using grep, sort and another command to print out the five counties with greatest population starting from 1898 (The file is much longer the example above is just a sample). I am kind of confused as to how I can do such a thing using grep and sort. I need to be able to output the solution in decreasing order. I was thinking I should first sort by the year and remove all years before 1898, and then sort again based on the population to get the most populous counties.

Your help is appreciated thank you.

Use awk to filter lines with year >1898, then sort by the population in descending order, then print the first 5 lines

from the command line

awk '$2>1898' test.txt  | sort -r | head -6

Print the first 6 line will also print the 5 records + header line.

I am an occasional awk user. My initial awk script was too complicated. Thanks @Jotne for a simple solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM