我正在搜索基于 Ips amd 进程的打开文件列表。我使用下面的命令
for i in `sudo netstat -tulpna|awk '{print $5}'|grep -E "[0-9]{3}"|grep -v "^192\|10"|cut -f1 -d ":"`;do sudo netstat -tulpna|awk '/XXX.XXX.XXX.XXX/ {print $7}';done
26181/java
26181/java
26181/java
26181/java
26181/java
26181/java
26181/java
26181/java
26181/java
26181/java
26181/java
26181/java
如果我添加单引号并且在 awk 条件 /XXX.XXX.XXX.XXX/ 下工作正常,我给出静态值它将打印第七列
但是如果我使用双引号和 /$i/ 变量
for i in `sudo netstat -tulpna|awk '{print $5}'|grep -E "[0-9]{3}"|grep -v "^192\|10"|cut -f1 -d ":"`;do sudo netstat -tulpna|awk "/$i/ {print $7}";done
tcp 0 0 XXX.XXX.XXX.XXX:443 XXX.XXX.XXX.XXX:62778 ESTABLISHED 26181/java
tcp 0 0 XXX.XXX.XXX.XXX:443 XXX.XXX.XXX.XXX:35708 ESTABLISHED 26181/java
tcp 0 0 XXX.XXX.XXX.XXX:443 XXX.XXX.XXX.XXX:40920 ESTABLISHED 26181/java
tcp 0 0 XXX.XXX.XXX.XXX:443 XXX.XXX.XXX.XXX:40918 ESTABLISHED 26181/java
tcp 0 0 XXX.XXX.XXX.XXX:443 XXX.XXX.XXX.XXX:31211 ESTABLISHED 26181/java
tcp 0 0 XXX.XXX.XXX.XXX:443 XXX.XXX.XXX.XXX:35708 ESTABLISHED 26181/java
tcp 0 0 XXX.XXX.XXX.XXX:443 XXX.XXX.XXX.XXX:40920 ESTABLISHED 26181/java
tcp 0 0 XXX.XXX.XXX.XXX:443 XXX.XXX.XXX.XXX:40918 ESTABLISHED 26181/java
tcp 0 0 XXX.XXX.XXX.XXX:443 XXX.XXX.XXX.XXX:31211 ESTABLISHED 26181/java
tcp 0 0 XXX.XXX.XXX.XXX:443 XXX.XXX.XXX.XXX:35708 ESTABLISHED 26181/java
tcp 0 0 XXX.XXX.XXX.XXX:443 XXX.XXX.XXX.XXX:40920 ESTABLISHED 26181/java
tcp 0 0 XXX.XXX.XXX.XXX:443 XXX.XXX.XXX.XXX:40918 ESTABLISHED 26181/java
tcp 0 0 XXX.XXX.XXX.XXX:443 XXX.XXX.XXX.XXX:31211 ESTABLISHED 26181/java
tcp 0 0 XXX.XXX.XXX.XXX:443 XXX.XXX.XXX.XXX:35708 ESTABLISHED 26181/java
tcp 0 0 XXX.XXX.XXX.XXX:443 XXX.XXX.XXX.XXX:40920 ESTABLISHED 26181/java
tcp 0 0 XXX.XXX.XXX.XXX:443 XXX.XXX.XXX.XXX:40918 ESTABLISHED 26181/java
tcp 0 0 XXX.XXX.XXX.XXX:443 XXX.XXX.XXX.XXX:31211 ESTABLISHED 26181/java
当它只应该打印第 7 列时。我在这里缺少什么
答案1
你的awk
脚本:
awk "/$i/ {print $7}"
这里,$7
由 shell 扩展并且很可能为空,导致命令
awk '/something/ {print }'
相反,您可以从 shell 中转义$
in :$7
awk "/$i/ {print \$7}"
awk
在这样的简短脚本中这是可以的。在更复杂的脚本中,人们可能应该传递$i
到awk
using-v variable="$i"
和 use variable
tomatch()
反对这些行(或使用~
asαГsнιη 显示)。
答案2
您应该首先将$i
变量 of传递for ...;do ... ;done
给awk
变量,然后将其值作为模式进行匹配,如下所示:
... | awk -v list="$i" '$0 ~ list {print $7}'; done