UNIX命令以查找得分第二高的学生的姓名 [英] A UNIX Command to Find the Name of the Student who has the Second Highest Score
问题描述
我是Unix编程的新手.你能帮我解决这个问题吗?例如,如果输入文件具有以下内容
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
输出将是
ABC
我尝试过类似的事情
sort -k3,3 -rn -t" " | head -n2 | awk '{print $2}'
推荐答案
使用 awk
awk 'NR>1{arr[$3]=$2} END {n=asorti(arr,arr_sorted); print arr[arr_sorted[n-1]]}'
演示:
$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
$
说明:
NR> 1
->跳过第一条记录
{arr [$ 3] = $ 2}
->创建带有标记的索引数组和名称作为值的关联数组
{arr[$3]=$2}
--> Create associtive array with marks as index and name as value
END
<-读取到文件结尾
END
<-- read till end of file
n = asorti(arr,arr_sorted)
<-对索引值(即标记)上的数组 arr
进行排序,并保存在 arr_sorted
中. n
=数组中元素的数量
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
将指向arr_sorted中的倒数第二个值(即标记)并打印相应的来自 arr
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
这篇关于UNIX命令以查找得分第二高的学生的姓名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!