這是我解釋我的問題的例子:
Bug Day 2022-01-13:
Security-Fail 248975
Resolve:
...
Bug Day 2022-01-25:
Security-Fail 225489
Security-Fail 225256
Security-Fail 225236
Resolve:
...
Bug Day 2022-02-02:
Security-Fail 222599
Resolve:
所以,我有一個包含多個安全漏洞的大檔案。我想獲得:
2022-01-13;248975
2022-01-25;225489,225256,225236
2022-02-02;222599
我雖然關于做類似的事情
bugDayNb=$(grep "Bug Day" | wc -l)
for i in $bugDayNb; do
echo "myBugsFile" | grep -A10 -m$i "Bug Day"
done
這個命令的問題是,如果有超過 10 個 Security-Fail,它就不起作用,如果我放一個“-A50”,它可能需要下一個 Bug Day 的下一個 Security-Fail。
所以我更喜歡從第 x 個“錯誤日”到第 x 個“解決”的sed或類似的方式
謝謝 !!
uj5u.com熱心網友回復:
這是一種方法:
$ awk '/^Bug Day/{d=$NF; s=""}
/^Security-Fail/{d = d s $NF; s=","}
/^Resolve:/{print d}' ip.txt
2022-01-13:248975
2022-01-25:225489,225256,225236
2022-02-02:222599
/^Bug Day/{d=$NF; s=""}d如果行以開頭Bug Day并初始化s為空字串 ,則將日期保存到變數{d=$NF; sub(/:$/, ";", d); s=""}如果需要;,請使用:
/^Security-Fail/{d = d s $NF; s=","}當行開始時Security-Fail將數字附加到d變數并設定s,以便進一步的附加將由,/^Resolve:/{print d}Resolve:看到時列印結果
uj5u.com熱心網友回復:
使用您顯示的示例,請嘗試以下awk程式。
awk '
/Bug Day/{
sub(/:$/,"",$NF)
bugVal=$NF
next
}
/^Security-Fail/{
secVal=(secVal?secVal ",":"")$NF
next
}
/^Resolve:/ && bugVal && secVal{
print bugVal";"secVal
bugVal=secVal=""
}
' Input_file
說明:為上述添加詳細說明。
awk ' ##Starting awk program from here.
/Bug Day/{ ##Checking condition if line contains Bug day then do following.
sub(/:$/,"",$NF) ##Substituting : at last of $NF in current line.
bugVal=$NF ##Creating bugVal which has $NF value in it.
next ##next will skip all further statements from here.
}
/^Security-Fail/{ ##Checking if line starts from Security-Fail then do following.
secVal=(secVal?secVal ",":"")$NF ##Creating secVal which has $NF value in it and keep adding value to it with delimiter of comma here.
next ##next will skip all further statements from here.
}
/^Resolve:/ && bugVal && secVal{ ##Checking condition if line starts from Resolve: and bugVal is SET and secVal is SET then do following.
print bugVal";"secVal ##printing bugVal semi-colon secVal here.
bugVal=secVal="" ##Nullifying bugVal and secVal here.
}
' Input_file ##mentioning Input_file name here.
uj5u.com熱心網友回復:
這可能對您有用(GNU sed):
sed -nE '/Bug Day/{:a;N;/Resolve/!ba;s/.* //mg;y/\n/,/;s/:,(.*),.*/;\1/p}' file
收集和之間的行Bug Day并Resolve相應地格式化。
如果您想選擇一天或幾天范圍,請使用:
sed -nE '/Bug Day/{x;s/^/x/;/^x{1,3}$/!{x;d};x
:a;N;/Resolve/!ba;s/.* //mg;y/\n/,/;s/:,/;/;s/(.*),.*/\1/p}' file
上面的命令顯示前 3 天,即 1 到 3
uj5u.com熱心網友回復:
請您嘗試一個awk解決方案:
awk '/^Bug Day/ {f=1; line=$0; next} # start of block
f {line=line ORS $0} # append the line if "f" is set
/^Security-Fail/ {g=1} # the block contains "Security-Fail"
/^Resolve/ {if (g) print line; f=g=0; line=""} # end of block
' input_file
如果您更喜歡單線:
awk '/^Bug Day/{f=1; line=$0; next} f{line=line ORS $0} /^Security-Fail/{g=1} /^Resolve/{if (g) print line; f=g=0; line=""}' input_file
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/465258.html
