A UNIX Command to Find the Name of the Student who has the Second Highest Score

╄→гoц情女王★ 提交于 2021-01-29 20:08:55

问题


I am new to Unix Programming. Could you please help me to solve the question. For example, If the input file has the below content

RollNo Name Score
234 ABC 70
567 QWE 12
457 RTE 56
234 XYZ 80
456 ERT 45

The output will be

ABC

I tried something like this

sort -k3,3 -rn -t" " | head -n2 | awk '{print $2}'

回答1:


Using awk

awk 'NR>1{arr[$3]=$2} END {n=asorti(arr,arr_sorted);  print  arr[arr_sorted[n-1]]}'

Demo:

$cat file.txt 
RollNo Name Score
234 ABC 70
567 QWE 12
457 RTE 56
234 XYZ 80
456 ERT 45
$awk 'NR>1{arr[$3]=$2} END {n=asorti(arr,arr_sorted);  print  arr[arr_sorted[n-1]]}'  file.txt 
ABC
$

Explanation:

NR>1 --> Skip first record

{arr[$3]=$2} --> Create associtive array with marks as index and name as value

END <-- read till end of file

n=asorti(arr,arr_sorted) <-- Sort array arr on index value(i.e marks) and save in arr_sorted. n= number of element in array

print arr[arr_sorted[n-1]]} <-- n-1 will point to second last value in arr_sorted (i.e marks) and print corresponding value from arr




回答2:


Your attempt is 90% correct just a single change Try this...it will work.

sort -k3,3 -rn -t" " | head -n1 | awk '{print $2}'

Instead of using head -n2 replace it with head -n1



来源:https://stackoverflow.com/questions/61607048/a-unix-command-to-find-the-name-of-the-student-who-has-the-second-highest-score

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!