Home > OS >  How to add lines from file where match is found in another file and merge into new file?
How to add lines from file where match is found in another file and merge into new file?

Time:11-22

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?

CodePudding user response:

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
) >Results.txt

CodePudding user response:

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?).

  • Related