簡體   English   中英

使用awk從文件中提取數據

[英]extract data from a file using awk

如何從以下數據中提取味精,sid:

alert tcp any any -> any any (msg: "this is a "dummy" rule (to test) the rule"; flow:to server; sid:1233; rev:1; no case; content: "nothing";)

輸出應該是這樣的:

這是一個“虛擬”規則(用於測試) 1233

您可能要嘗試使用sed:

sed 's/.*msg: "\([^;]*\)";.*sid:\([0-9]*\).*/\1|\2/' file

它使用反向引用捕獲並輸出所需的字符串。

嘗試這個 -

awk -F'[:;]' '{print substr($2,3,(length($2)-3)),"| " $6}' f
this is a "dummy" rule (to test) the rule | 1233

要么

awk -F'[:;]' '{print substr($2,3,(length($2)-3)),v OFS $6}' v="|" f
this is a "dummy" rule (to test) the rule | 1233

要么

awk -v OFS=" | " -F'[:;]' '{gsub(/^[ "]+|["]+$/,"",$2);print $2 OFS $6}' f
this is a "dummy" rule (to test) the rule | 1233

鑒於:

$ echo "$txt"
alert tcp any any -> any any (msg: "this is a "dummy" rule (to test) the rule"; flow:to server; sid:1233; rev:1; no case; content: "nothing";)

您可以使用Bash正則表達式:

$ [[ $txt =~ msg:\ \"([^;]*)\"\;.*sid:([^;]*) ]] && 
         printf "%s | %s" "${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}"
this is a "dummy" rule (to test) the rule | 1233

我選擇Perl是因為它支持非貪婪的運算符,並且將在所有平台(便攜式)上均相同:

$ echo "$b"
alert tcp any any -> any any (msg: "this is a "dummy" rule (to test) the rule"; flow:to server; sid:1233; rev:1; no case; content: "nothing";)

$ echo "$b" |perl -pe 's/(.*msg: ?)(.*?)(\;.*?).*sid:(.*?)\;.*/\2|\4/'
"this is a "dummy" rule (to test) the rule"|1233

還有一個awk-僅限於GNU awk:

$ echo "$b" |awk '{match($0,/(.*msg: )(\".+\"[^;]*)(.*sid:)(.[^;]*)/,a);print a[2] "|" a[4]}'
"this is a "dummy" rule (to test) the rule"|1233

我嘗試用awk和split fucntion:

awk -F ';' '
    {
                    for(i=1;i<=NF;i++)
            {
                            if(match($i,"msg")>0)
                    {
                            split($i, array2, ":")
                            message=array2[2]
                    }
           }

           print message
    }'  >> $file

完成

對我來說很好

awk -F\" '{print $2,$3,$4" | " substr($5,23,4)}' OFS='"' file

this is a "dummy" rule (to test) the rule | 1233

暫無
暫無

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

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