如何在 awk 中使用帶有變數的模式

如何在 awk 中使用帶有變數的模式

我的文件如下;我想顯示百分比高於 80 的學生的記錄。

Studid    StudName     Asp.Net   DBMS     Unix
   1       Ani         75        62       80
   2       George      90        95       82
   3       Jake        45        30       40
   4       Dennie      89        92       90

所以我使用了以下程式碼:

awk '(($3+$4+$5)/3)>80 {print}' stud

它有效,但我想將這些列分配給變量,然後顯示輸出。所以我嘗試了下面的程式碼,但它不起作用

awk 'total=$3+$4+$5, per=total/3, per>80 {print}' stud

有變數的解決方案嗎?

答案1

您可以將邏輯從規則節成行動

awk '{total=$3+$4+$5; per=total/3; if (per>80) print}' stud
   2       George      90        95       82
   4       Dennie      89        92       90

請注意,這會嘗試以算術方式計算列標題 - 這“有效”,因為在 中awk,當您嘗試對非數字字段進行算術運算時,非數字字段將被視為零- 但會導致標題行被打印,例如,如果您將測試更改為per<80.恕我直言,更好的方法是使用next規則的操作明確跳過標題行NR==1

awk 'NR==1 {next} {total=$3+$4+$5; per=total/3; if (per>80) print}' stud
   2       George      90        95       82
   4       Dennie      89        92       90

或者,如果您想要標題,請明確列印它

awk 'NR==1 {print; next} {total=$3+$4+$5; per=total/3; if (per>80) print}' stud
Studid    StudName     Asp.Net   DBMS     Unix
   2       George      90        95       82
   4       Dennie      89        92       90

答案2

嘗試:

awk ' 
# if /^Studid/ is matched move to the next record (row) of the input text
/^Studid/ { next }
{               
    total=$3+$4+$5
    per=total/3
    if (per > 80)  
        print 
}' stud

輸出

   2       George      90        95       82
   4       Dennie      89        92       90

相關內容