簡體   English   中英

當awk中的模式規則不正確時執行的命令,怎么了?

[英]a command executed when pattern rule is not true in awk, what's wrong?

再次出現一個奇怪的awk現象..(這一直在發生:))
我在下面有一個文件aaa。

[first]
aaa
bbb
[second]
ccc
ddd
eee
[third]
fff
ggg
hhh
iii

我正在嘗試打印每個部分的行號,該行號以包含在括號中的標題開頭。 因此,我在下面編寫了一個簡單的awk腳本CntSecLines.awk(正在調試,因此帶有一些打印件)。

 /\[/{print "header found : "; print $keep " : " cnt; keep=$1; cnt=0}
!/\[/{print "header not found"; cnt = cnt+1; print "keep = " $keep;}

以下是aaa的執行結果。

ckim@stph45:~/test] awk -f CntSecLines.awk aaa
header found : 
[first] : 
header not found
keep = aaa
header not found
keep = bbb
header found : 
[second] : 2
header not found
keep = ccc
header not found
keep = ddd
header not found
keep = eee
header found : 
[third] : 3
header not found
keep = fff
header not found
keep = ggg
header not found
keep = hhh
header not found
keep = iii

我打算僅在有節標題時才對其進行更新。 但是為什么變量“ keep”每行都會更新? 當我打印變量$ keep時,我們可以看到它正在每條非節頭行中進行更新。

awk ,不是bash awk您不使用$來獲取變量值(當然,有例外,例如位置參數$1$2 ...)。

awk '
   /\[/{print "header found : "; print keep " : " cnt; keep=$1; cnt=0}
   !/\[/{print "header not found"; cnt = cnt+1; print "keep = " keep;}
' <<EOF
[first]
aaa
bbb
[second]
ccc
ddd
eee
[third]
fff
ggg
hhh
iii
EOF

將輸出:

header found : 
 : 
header not found
keep = [first]
header not found
keep = [first]
header found : 
[first] : 2
header not found
keep = [second]
header not found
keep = [second]
header not found
keep = [second]
header found : 
[second] : 3
header not found
keep = [third]
header not found
keep = [third]
header not found
keep = [third]
header not found
keep = [third]

repl測試。

我相信awk會將$keep解釋為像$的字符串[blabla] ,例如$"[blabla]" ,然后將"[blabla]"從字符串轉換為數字,結果為0 ,因此$keep是解釋為$0 ,將打印整行。

我將您的要求解釋為“計算每個用括號分隔的部分中的行數”。

$ awk '/^\[.*\]$/ {c=0; print; next} {print ++c, $0}' file
[first]
1 aaa
2 bbb
[second]
1 ccc
2 ddd
3 eee
[third]
1 fff
2 ggg
3 hhh
4 iii
  • /^\\[.*\\]$/如果記錄以文字[開始,以文字]結尾

  • {c=0; print; next} {c=0; print; next} -設置/重置計數,打印記錄,跳過剩余規則

  • {print ++c, $0}對於不匹配的第一個規則記錄,打印預遞增計數時,輸出字段分隔符,和記錄$0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM