Alex Georgio
Alex Georgio

Reputation: 41

Extracting largest values from certain columns in Bash

Please tell me how to write a bash script that finds the following:

  1. the lines containing the 5 largest values from column 1

  2. the line containing the second largest value from column 1

  3. the line number of the lines containing the 5 largest values from column 1

Upvotes: 0

Views: 59

Answers (1)

Reut Sharabani
Reut Sharabani

Reputation: 31339

You can use sort with head and tail:

# the lines containing the 5 largest values from column 1
sort -n somefile.csv --reverse | head -n 5
# the line containing the second largest value from column 1
sort -n somefile.csv --reverse | head -n 2 | tail -n 1

For the last part you need the line numbers as well, so add them using cat --number and use the same method:

cat --number somefile.csv | sort -nk2 --reverse | head -n 5

Note that column 2 is used as the key in the last command since the first column contains the line numbers.

Upvotes: 1

Related Questions