0

I have a text file with a list of addresses from all recent connections. I ran the following command:

netstat -natu | grep 'ESTABLISHED' > temp.txt 

I then proceeded to filter everything in the file but the IPs with:

grep -oP '(\d{1,3}\.){1,3}\d{1,3}' temp.txt > IPs.txt  

Now I am wondering if there is a way I can find a certian IP in this text file, and (if possible) remove the line completely. Basically filter out local host addresses (127.0.0.0) so I am left with only the foreign addresses. But I'm not sure I understand how I should be doing this.

Would it be easier to filter out the local IPs somewhere during this process, or to simply filter them out of the resulting text file?

If anyone has any ideas, I would be happy to hear them. I'm not very familiar with grep, but I am slowly learning... Thank you in advance.

1 Answer 1

0

The foreign addresses are already in a different column in the output of netstat. Instead of grep -o which prints both local and foreign IPs, use awk to print just the foreign IPs:

netstat -natu | grep ESTABLISHED | awk '{print $5}' | cut -d: -f1 > IPs.txt

That also gives you the option of removing the -n from netstat so you can see the names instead of IPs.

And if you want to remove duplicates, pipe that whole thing to sort -u


Edit:
And to answer the actual question asked in the title, you can remove all lines in the file that contain exactly the loopback IP with the following command:

sed -i '/^127.0.0.1$/ d' temp.txt

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .