Monday, May 9, 2022

[SOLVED] Finding second highest salary using awk

Issue

I have a file as follows

1 rob   hr 10000
2 charls it 20000
4 kk  Fin 30000
5 km  it 30000
6 kl  it 30000
7 mark  hr 10000
8 kc  it 30000
9 dc  fin 40000
10 mn  hr  40000
3 abi  it 20000

where the 4rth column contains the salary of an individuals in column 2. I want to get all the records with 2nd highest salary (or nth highest salary to be general). Sample output :

 4 kk  Fin 30000
 5 km  it 30000
 8 kc  it 30000
 6 kl  it 30000

I have tried this :

sort -k4,4 employee.txt  | awk 'NR==1{a=$4;next}{if($4>a){print $0 ;exit} else next;}'   | a=`awk '{ print $4}'` |  awk -v b=$a  '$4==b'  < cat employee.txt

but this is not giving any output . Any smart suggestions please ?


Solution

awk to the rescue!

sort -k4nr file | 
awk '!($4 in a){c++; a[$4]} c==2'

4       kk      Fin     30000
5       km      it      30000
6       kl      it      30000
8       kc      it      30000


Answered By - karakfa
Answer Checked By - Mildred Charles (WPSolving Admin)