How to substract two stdout lists in linux bash

Viewed 58

heed help.

I have one list "A" from

netstat -ntlp | grep -oP ":[:1]?[:1]?(.*)+" | grep -oP "\d\d+"

it looks like

80
443
8080
22
25

I have another list "B" from

ufw status numbered | grep -oP "\] \d+" | grep -oP "\d+"

it looks as

80
443
22

So i want to know, which ports are listening, but not open with ufw, i.e. substract ["A"]-["B"] and going to see

8080
25

with some command like

netstat -ntlp | grep -oP ":[:1]?[:1]?(.*)+" | grep -oP "\d\d+" | SELECT ALL NOT IN `ufw status numbered | grep -oP "\] \d+" | grep -oP "\d+"`

How to do this?

4 Answers

You may use grep:

grep -vxFf <(cmd2) <(cmd1)

Here replace cmd1 with netstat ... command and replace cmd2 with ufw ... command.

Typically it's comm job:

netstat -ntlp | grep -oP ":[:1]?[:1]?(.*)+" | grep -oP "\d\d+" |
sort | comm -23 - <(ufw status numbered | grep -oP "\] \d+" | grep -oP "\d+" | sort)

You can check the uniq -u command:

http://man7.org/linux/man-pages/man1/uniq.1.html

You pass a group of lines to uniq -d and redirect to an output. It will print only the duplicated ones. So you just need to aggregate both results from list A and list B into a text:

List A:

netstat -ntlp | grep -oP ":[:1]?[:1]?(.*)+" | grep -oP "\d\d+" >> output.txt

List B:

ufw status numbered | grep -oP "\] \d+" | grep -oP "\d+" > output.txt >> output.txt`

(NOTE: You use '>>' over '>' to append the content to end of the file. So make sure to clean it on each iteration!)

Then:

uniq -u output.txt

You can redirect the uniq -u output too, if needed:

uniq -u output.txt > gotuniques.txt

Edit: formatting Edit2: I was confused by -d when the answer requires -u.

This solution requires pre-sorting of the outputs:

$ netstat -ntlp | grep -oP ":[:1]?[:1]?(.*)+" | grep -oP "\d\d+" | sort > A
                                                                 ^^^^^^
$ ufw status numbered | grep -oP "\] \d+" | grep -oP "\d+" | sort > B
                                                           ^^^^^^

Items unique to A:

$ comm -23 A B
25
8080
$ 

... but also, in case you require, items unique to B:

$ comm -13 A B
$ 

... and items common to A and B:

$ comm -12 A B
22
443
80
$ 

See man comm for details.

Related