如果这些变量中的任何一个为真,我想要打印代码。这不是我真正的代码,这只是一个例子
read -p "enter protocol: " protocol
read -p "enter src ip: " srcip
read -p "enter dst ip: " dstip
read -p "enter src port: " srcport
read -p "enter dst port: " dstport
等等
awk -F"," -v pro="$protocol" -v sip="$srcip" -v dip="$dstip" -v sport="$srcport" -v dport="$dstport" '{ if(pro == "tcp" && sip == "10" && dip == "30" && sport == "4" && dport == "1")
print $1,$2,$3,$4,$5,$6,$7}' test.txt > test2.txt
为了更清楚,我会用另一种方式写在这里
PROTOCOL,SRC IP,SRC PORT,DEST IP,DEST port
tcp .10 29 .30 300
udp .34 545 .94 90
tcp .23 233 .23 42
我需要其中任何三个变量与用户输入匹配,打印该行。
我已经尝试了下面的代码,但给我一个错误。
awk -F"," -v pro="$protocol" -v sip="$srcip" -v dip="$dstip" -v sport="$srcport" -v dport="$dstport" 'BEGIN {if ($3 ~ pro) count++; if ($4 ~ sip) count++; if ($5 == sport) count++; if ($6 ~ dip) count++; if ($7 == dport) count++; count>=3; { print $3,$4,$5,$6,$7 }' test.txt > test2.txt
error: ^ syntax error
^ unexpected newline or end of string
答案1
未经测试:
awk -F',' -v pro="$protocol" -v sip="$srcip" -v dip="$dstip" -v sport="$srcport" -v dport="$dstport" '
{
c = 0
c += (pro == "tcp")
c += (sip == "10")
c += (dip == "30")
c += (sport == "4")
c += (dport == "1")
}
c > 2
' test.txt
c > 2 { print $1,$2,$3,$4,$5,$6,$7 }
如果您确实只想打印字段的子集而不是整行,请执行此操作。
答案2
#!/bin/bash
read -p "enter the src ip:" srcip
read -p "enter the des ip:" desip
read -p "enter the src port:" srcport
awk -v srcip="$srcip" -v desip="$desip" -v srcport="$srcport" '($2 == srcip||$4 == desip || $5 == srcport){print $0}' filename
测试并运行良好
输出
输入src ip:.10 输入des ip:.30 输入src port:34
TCP .10 29 .30 300