我是 awk 的新手,我正在嘗試自己學習 bash,我發現 awk 真的很有趣,我只是想知道如何減去兩行的值
34 43 67 87
21 22 64 43
這樣我就達到了所需的輸出
13 21 3 44
我的嘗試
awk 'BEGIN{ FS = "\n" }{avgShirts=$1-$2}{print avgShirts}'
由于它只有兩行,我通過指定欄位分隔符是一個新行來嘗試,但它沒有用。
uj5u.com熱心網友回復:
假設/理解:
- 輸入正好由 2 行組成
- 兩行具有相同數量的欄位/列
輸入:
$ cat 2rows.dat
34 43 67 87
21 22 64 43
一個awk想法:
awk '
NR==1 { for (i=1;i<=NF;i ) # 1st line, loop through each field and ...
fld[i]=$i # store each field in array fld[]
next # skip the rest of the awk script and proceed to the next input line
}
{ for (i=1;i<=NF;i ) { # 2nd line, loop through each field and ...
line=line pfx (fld[i]-$i) # build output line based on difference of fields from 1st and 2nd lines
pfx=OFS # 1st pass through loop pfx="", rest of loop pfx=" "
}
print line # print line of differences
}
' 2rows.dat
這會產生:
13 21 3 44
awk在計算總和時列印總和的另一種想法:
awk '
NR==1 { for (i=1;i<=NF;i )
fld[i]=$i
next
}
{ for (i=1;i<=NF;i ) {
printf "%s%s", pfx, (fld[i]-$i) # print prefix and current diff, since there is no "\n" we remain on the same output line for the next pass through the loop
pfx=OFS
}
print "" # terminate line; same effect as: printf "\n"
}
' 2rows.dat
這也會產生:
13 21 3 44
uj5u.com熱心網友回復:
你可以做:
awk 'FNR%2{for (i=1;i<=NF;i ) arr[i]=$i; next}
{for (i=1;i<=NF;i ) $i=arr[i]-$i} 1' file
13 21 3 44
解釋:
# save every odd line
FNR%2{for (i=1;i<=NF;i ) arr[i]=$i; next}
# every even line, subtract this field from the previous and print
{for (i=1;i<=NF;i ) $i=arr[i]-$i} 1'
uj5u.com熱心網友回復:
$ awk '
NR==1 { split($0,minuends); next }
{
for (i=1; i<=NF; i ) {
printf "%d%s", minuends[i] - $i, (i<NF ? OFS : ORS)
}
}
' file
13 21 3 44
如果您不熟悉 awk,請在手冊頁中查找 NR、NF、OFS、ORS 和 split()。您可以從 Arnold Robbins 的 Effective AWK Programming,第 5 版一書中學習 awk。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/344667.html
