'Finding second highest salary using awk

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 1:[1]

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

Solution 2:[2]

For highest salary you can simply use

sort text.txt | awk '!($4 in a){c++; a[$4]} c==2'

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 karakfa
Solution 2 Dharman