如何用键盘从输入模式打印每个块?

时间:2018-06-22 07:38:00

标签: bash shell

示例文件:

TCP  192.168.56.224:80 rr
  -> 192.168.56.112:80            Route   1      0          0
  -> 192.168.56.113:80            Route   1      0          0
TCP  192.168.56.225:80 rr
  -> 192.168.56.109:80            Route   1      0          0
  -> 192.168.56.110:80            Route   1      0          0
TCP  192.168.56.226:80 rr
  -> 192.168.56.3:80              Route   1      0          0
UDP  192.168.56.224:80 rr
  -> 192.168.56.112:80            Route   1      0          0
  -> 192.168.56.113:80            Route   1      0          0
UDP  192.168.56.225:80 rr
  -> 192.168.56.109:80            Route   1      0          0
  -> 192.168.56.110:80            Route   1      0          0
UDP  192.168.56.226:80 rr
  -> 192.168.56.3:80              Route   1      0          0
  -> 192.168.56.120:80            Route   1      0          0

我想根据键盘输入的模式并使用awk或sed命令打印相应的TCP和UDP块。

示例:输入192.168.56.110:80的值,那么我要打印的结果是:

TCP  192.168.56.225:80 rr
  -> 192.168.56.109:80            Route   1      0          0
  -> 192.168.56.110:80            Route   1      0          0
UDP  192.168.56.225:80 rr
  -> 192.168.56.109:80            Route   1      0          0
  -> 192.168.56.110:80            Route   1      0          0

请帮助我。

2 个答案:

答案 0 :(得分:0)

能否请您尝试以下操作,如果有帮助,请告诉我。

cat script.ksh
echo "Please enter the ip address which you want to print:"
read value

awk -v val="$value" '/^TCP/||/^UDP/{value=""}!flag{value=value?value ORS $0:$0} $0 ~ val{flag=1} flag{print value;value=flag=""}'  Input_file

它将要求运行脚本的人输入IP,当用户输入IP时,它将查找到Input_file。

答案 1 :(得分:0)

这是使用gnu awk的替代方法:

awk -v RS='(^|\n)(TC|UD)P[[:blank:]]' -v ip='192.168.56.110:80' 'index($0, ip) {
print RT $0}' file

TCP  192.168.56.225:80 rr
  -> 192.168.56.109:80            Route   1      0          0
  -> 192.168.56.110:80            Route   1      0          0

UDP  192.168.56.225:80 rr
  -> 192.168.56.109:80            Route   1      0          0
  -> 192.168.56.110:80            Route   1      0          0