-1

I have file IP.txt:

192.168.69.100
192.168.69.141

I also have file Ports.txt:

open port: 21 on IP: 192.168.69.100 with banner:
220 FTP server ready
open port: 22 on IP: 192.168.69.100 with banner:
SSH-OpenSSH
open port: 21 on IP: 192.168.69.141 with banner:
220 FTP server ready
open port: 22 on IP: 192.168.69.141 with banner:
SSH-OpenSSH

I need the 2 files merged into Results.txt, like so:

192.168.69.100
open port: 21 on IP: 192.168.69.100 with banner:
220 FTP server ready
open port: 22 on IP: 192.168.69.100 with banner:
SSH-OpenSSH

192.168.69.141
open port: 21 on IP: 192.168.69.141 with banner:
220 FTP server ready
open port: 22 on IP: 192.168.69.141 with banner:
SSH-OpenSSH

Note how there is a new line empty space after the port's banner and before the next IP.

So, to grab the open port... on 192.168.69.... line and the line below it, then place them after the 192.168.69.... line, then finally adding a new empty line.

How can i achieve this?

2 Answers2

0

Loop over the IP-Addresses and for each one, use grep -A1 to print matching lines plus the one after. Something like (untested):

for IP in `cat IP.txt`; do
      echo $IP
      grep -A1 $IP Ports.txt
      echo
done >Results.txt
treuss
  • 1,913
  • 1
  • 15
  • Missing a `done`. Unnecessary `()`. Using backticks. `echo`. Unquoted variables. Uppercase variable. And last but not least [for-in-cat](https://stackoverflow.com/questions/1521462/looping-through-the-content-of-a-file-in-bash). – Biffen Nov 22 '22 at 12:35
  • can someone fix this? it is not working with what i have attempted thus far – Robot110010 Nov 22 '22 at 22:36
0

Using printf with grep and sed:

while read -r ip ; do printf "%s\n%s\n\n" "$ip" $(grep -A1 "$ip" Ports.txt) | sed '/^--$/d' ; done < IP.txt

Output:

192.168.69.100
open port: 21 on IP: 192.168.69.100 with banner:
220 FTP server ready
open port: 22 on IP: 192.168.69.100 with banner:
SSH-OpenSSH

192.168.69.141
open port: 21 on IP: 192.168.69.141 with banner:
220 FTP server ready
open port: 22 on IP: 192.168.69.141 with banner:
SSH-OpenSSH

Depending on your version of grep you may be able to replace the pipe to sed with the undocumented grep switch --no-group-separator or --group-separator "" (How do I get rid of "--" line separator when using grep with context lines?).

Script details: For each IP address in the IP.txt file search (via grep) for the IP address in the Ports.txt file plus the line following any IP match. Remove the contextual grouping separator (--) using sed. Format the output using printf

j_b
  • 1,975
  • 3
  • 8
  • 14