我正在嘗試使用sed從第一個模式的行開始洗掉文本,直到第二次出現結束模式的行。
例如,第一個模式是BEGIN,結束模式是BREAKPOINT。
輸入示例:
qq
ww
BEGIN
ab
ef
BREAKPOINT
ij
mn
BREAKPOINT
kk
BREAKPOINT
zz
yy
xx
BEGIN
ab
ef
BREAKPOINT
ij
mn
BREAKPOINT
pp
預期輸出:
qq
ww
kk
BREAKPOINT
zz
yy
xx
pp
您能否告訴我如何實作這一目標,或者另一種方法?
PS。我只知道如何在第一個模式之間顯示文本,直到第二次出現結束模式,但我不知道如何洗掉它們。
sed -n '/BEGIN/{:a;N;s/BREAKPOINT/&/2p;Ta}' file
謝謝。
uj5u.com熱心網友回復:
在. sed_ sed最好切換到更易讀的腳本語言:
awk '/^BEGIN$/ && !s { s=2 }
!s
/^BREAKPOINT$/ && s { s-- }' file
簡而言之,該變數s會跟蹤我們是否已經看到了開始分隔符,如果看到了,我們希望在恢復列印輸入行之前看到多少次終止分隔符。
uj5u.com熱心網友回復:
僅使用您展示的示例,請嘗試以下awk代碼,使用 GNU 撰寫和測驗awk。
awk '
/^BEGIN/,/^BREAKPOINT/{
flag=1
next
}
flag && /BREAKPOINT/{
flag=""
next
}
!flag
' Input_file
說明:為上述添加詳細說明。
awk ' ##Starting awk program from here.
/^BEGIN/,/^BREAKPOINT/{ ##Checking range from line starts from BEGIN till line starts BREAKPOINT then do following.
flag=1 ##Setting flag to 1 here.
next ##next will skip all further statements from here.
}
flag && /BREAKPOINT/{ ##Checking condition if flag is SET and BREAKPOINT is found then do following.
flag="" ##Nullifying flag here.
next ##next will skip all further statements from here.
}
!flag ##Checking condition if flag is NULL then print current line.
' Input_file ##Mentioning Input_file name here.
uj5u.com熱心網友回復:
一個perl:
perl -0777 -pe 's/^BEGIN[\s\S]*?^BREAKPOINT[\s\S]*?^BREAKPOINT\R//gm' file
要么,
perl -0777 -pe 's/^BEGIN(?:[\s\S]*?^BREAKPOINT\R){2}//gm' file
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/434597.html
上一篇:重命名多個子檔案夾中的檔案
