首页 > 解决方案 > 使用数学分数使用 awk 命令查找记录

问题描述

编写unix命令,显示数学成绩超过80分的学生的所有领域,并且数学成绩应该是所有科目中的最高分,而且输出应该是学生的std(standard)升序

输入:

roll,name,std,science_marks,math_marks,college
1,A,9,60,86,SM
2,B,10,85,80,DAV
3,C,10,95,92,DAV
4,D,9,75,92,DAV

输出:

1|A|9|60|86|SM
4|D|9|75|92|DAV

我的代码:

awk 'BEGIN{FS=',' ; OFS="|"} {if($4<$5 && $5>80){print $1,$2,$3,$4,$5,$6}}'

但我收到了意外的令牌错误,请帮助我。

    Error Message on my Mac System Terminal:
awk: syntax error at source line 1
     context is
        BEGIN >>>  {FS=, <<< 
    awk: illegal statement at source line 1

标签: unixawk

解决方案


您能否尝试在 GNU 中使用显示的示例进行跟踪、编写和测试awk。这个答案没有硬编码它收集的字段编号,其中包含数学并相应地检查其余行。

awk '
BEGIN{
  FS=","
  OFS="|"
}
FNR==1{
  for(i=1;i<=NF;i++){
    if($i=="math_marks"){ field=i }
  }
  next
}
{
  for(i=3;i<=(NF-1);i++){
    max=(max>$i?(max?max:$i):$i)
  }
  if(max==$field && $field>80){ $1=$1; print }
  max=""
}
'  Input_file

说明:为上述添加详细说明。

awk '                                               ##Starting awk program from here.
BEGIN{                                              ##Starting BEGIN section of code here.
  FS=","                                            ##Setting field separator as comma here.
  OFS="|"                                           ##Setting output field separator as | here for all lines.
}
FNR==1{                                             ##Checking condition if its first line then do following.
  for(i=1;i<=NF;i++){                               ##Going through all fields here.
    if($i=="math_marks"){ field=i }                 ##Checking if a field value is math_marks then set field to tht field numner here.
  }
  next                                              ##next will skip all further statements from here.
}
{
  for(i=3;i<=(NF-1);i++){                           ##Going through from 3rd field to 2nd last field here.
    max=(max>$i?(max?max:$i):$i)                    ##Creating max variable which checks its value with current field and sets maximum value by comparison here.
  }
  if(max==$field && $field>80){ $1=$1; print }      ##After processing of all fields checking if maximum and field value is equal AND math number field is greater than 80 then print the line.
  max=""                                            ##Nullifying max var here.
}
'  Input_file                                       ##Mentioning Input_file name here.

推荐阅读