如何减去 linux bash 中的两个标准输出列表
How to substract two stdout lists in linux bash
注意帮助。
我有一份来自
的列表"A"
netstat -ntlp | grep -oP ":[:1]?[:1]?(.*)+" | grep -oP "\d\d+"
看起来像
80
443
8080
22
25
我有另一个列表 "B" 来自
ufw status numbered | grep -oP "\] \d+" | grep -oP "\d+"
它看起来像
80
443
22
所以我想知道哪些端口正在侦听,但未使用 ufw 打开,即减去 ["A"]-["B"]
去看看
8080
25
使用像
这样的命令
netstat -ntlp | grep -oP ":[:1]?[:1]?(.*)+" | grep -oP "\d\d+" | SELECT ALL NOT IN `ufw status numbered | grep -oP "\] \d+" | grep -oP "\d+"`
如何操作?
可以查看uniq -u
命令:
http://man7.org/linux/man-pages/man1/uniq.1.html
您将一组行传递给 uniq -d 并重定向到输出。它只会打印重复的。
所以你只需要将列表 A 和列表 B 的结果聚合到一个文本中:
列表 A:
netstat -ntlp | grep -oP ":[:1]?[:1]?(.*)+" | grep -oP "\d\d+" >> output.txt
列表 B:
ufw status numbered | grep -oP "\] \d+" | grep -oP "\d+" > output.txt
>> output.txt`
(注意:您使用“>>”而不是“>”将内容附加到文件末尾。因此请务必在每次迭代时清除它!)
然后:
uniq -u output.txt
如果需要,您也可以重定向 uniq -u 输出:
uniq -u output.txt > gotuniques.txt
编辑:格式化
Edit2:当答案需要 -u 时,我被 -d 弄糊涂了。
您可以使用 grep
:
grep -vxFf <(cmd2) <(cmd1)
此处将cmd1
替换为netstat ...
命令,将cmd2
替换为ufw ...
命令。
通常是 comm
工作:
netstat -ntlp | grep -oP ":[:1]?[:1]?(.*)+" | grep -oP "\d\d+" |
sort | comm -23 - <(ufw status numbered | grep -oP "\] \d+" | grep -oP "\d+" | sort)
此解决方案需要对输出进行预排序:
$ netstat -ntlp | grep -oP ":[:1]?[:1]?(.*)+" | grep -oP "\d\d+" | sort > A
^^^^^^
$ ufw status numbered | grep -oP "\] \d+" | grep -oP "\d+" | sort > B
^^^^^^
A 独有的物品:
$ comm -23 A B
25
8080
$
...而且,如果您需要,B 独有的项目:
$ comm -13 A B
$
...以及 A 和 B 共有的项目:
$ comm -12 A B
22
443
80
$
详情见man comm
。
注意帮助。
我有一份来自
的列表"A"netstat -ntlp | grep -oP ":[:1]?[:1]?(.*)+" | grep -oP "\d\d+"
看起来像
80
443
8080
22
25
我有另一个列表 "B" 来自
ufw status numbered | grep -oP "\] \d+" | grep -oP "\d+"
它看起来像
80
443
22
所以我想知道哪些端口正在侦听,但未使用 ufw 打开,即减去 ["A"]-["B"] 去看看
8080
25
使用像
这样的命令netstat -ntlp | grep -oP ":[:1]?[:1]?(.*)+" | grep -oP "\d\d+" | SELECT ALL NOT IN `ufw status numbered | grep -oP "\] \d+" | grep -oP "\d+"`
如何操作?
可以查看uniq -u
命令:
http://man7.org/linux/man-pages/man1/uniq.1.html
您将一组行传递给 uniq -d 并重定向到输出。它只会打印重复的。 所以你只需要将列表 A 和列表 B 的结果聚合到一个文本中:
列表 A:
netstat -ntlp | grep -oP ":[:1]?[:1]?(.*)+" | grep -oP "\d\d+" >> output.txt
列表 B:
ufw status numbered | grep -oP "\] \d+" | grep -oP "\d+" > output.txt
>> output.txt`
(注意:您使用“>>”而不是“>”将内容附加到文件末尾。因此请务必在每次迭代时清除它!)
然后:
uniq -u output.txt
如果需要,您也可以重定向 uniq -u 输出:
uniq -u output.txt > gotuniques.txt
编辑:格式化 Edit2:当答案需要 -u 时,我被 -d 弄糊涂了。
您可以使用 grep
:
grep -vxFf <(cmd2) <(cmd1)
此处将cmd1
替换为netstat ...
命令,将cmd2
替换为ufw ...
命令。
通常是 comm
工作:
netstat -ntlp | grep -oP ":[:1]?[:1]?(.*)+" | grep -oP "\d\d+" |
sort | comm -23 - <(ufw status numbered | grep -oP "\] \d+" | grep -oP "\d+" | sort)
此解决方案需要对输出进行预排序:
$ netstat -ntlp | grep -oP ":[:1]?[:1]?(.*)+" | grep -oP "\d\d+" | sort > A
^^^^^^
$ ufw status numbered | grep -oP "\] \d+" | grep -oP "\d+" | sort > B
^^^^^^
A 独有的物品:
$ comm -23 A B
25
8080
$
...而且,如果您需要,B 独有的项目:
$ comm -13 A B
$
...以及 A 和 B 共有的项目:
$ comm -12 A B
22
443
80
$
详情见man comm
。