Home > Back-end >  Have script find all lines containing x, prepend these lines to each line that follows unless the li
Have script find all lines containing x, prepend these lines to each line that follows unless the li

Time:10-04

I have a file called file.txt which contains either an IP or a FQDN, followed by ports that were found to be open. I want my bash script to prepend all ports with their associated IP/FQDN (always above them in the file), replace the forward slash with a whitespace, and then delete the IP/FQDN line that isn't associated with a port.

Breaking it down, I thought:

  1. Read the next line
  2. If the line contains a "." in it (IP or FQDN), prepend it into all following lines, unless:
  3. If the following line has a "." in it (another IP or FQDN), make that line the new one to prepend and repeat the process for all following lines
  4. Replace all "/" with a " " (one single whitespace)
  5. Remove all lines that are not associated with a port (probably easier just to grep for "tcp" and "udp" as that will display all open ports with associated IP/FQDN

To make it easier, I can easily create a tmp file if necessary within the process. I have tried various iterartions of "while" and "if" and nothing seems to work...!

E.g:

cat file.txt

www.thisisawebsite.com:
80/tcp
443/tcp
500/udp
192.168.1.5:
80/tcp
dev.anothersite.co.uk:
22/tcp
443/tcp
5050/udp
21000/tcp
10.10.10.10:
4000/udp
8000/udp

Then, running the bash script, it should become:

www.thisisawebsite.com:80 tcp
www.thisisawebsite.com:443 tcp
www.thisisawebsite.com:500 udp
192.168.1.5:80 tcp
dev.anothersite.co.uk:22 tcp
dev.anothersite.co.uk:433 tcp
dev.anothersite.co.uk:5050 udp
dev.anothersite.co.uk:21000 tcp
10.10.10.10:4000 udp
10.10.10.10:8000 udp

Thanks for any help.

CodePudding user response:

Looks like a job for awk:

awk -F/ '/\./ {d=$0; next} {print d":"$1, $2}'
  • Related