Search code examples
bashawksedgrepcut

Extracting content of a file in bash


I have a file with a content like: (This is nmap output)

Nmap scan report for x.x.x.x
Host is up (0.12s latency).
PORT   STATE SERVICE
23/tcp open  telnet
| telnet-brute: 
|   Accounts
|     var1:var2
|   Statistics
|     Performed 5 guesses in 3 seconds, average tps: 1
|   
|_ ERROR: Too many retries, aborted ...

Nmap scan report for y.y.y.y
Host is up (0.17s latency).
PORT   STATE SERVICE
23/tcp open  telnet
| telnet-brute: 
|   Accounts
|     var3:var4
|   Statistics
|_    Performed 2 guesses in 13 seconds, average tps: 0

Nmap scan report for z.z.z.z
Host is up (0.19s latency).
PORT   STATE SERVICE
23/tcp open  telnet
| telnet-brute: 
|   Accounts
|     No valid accounts found

I want to extract this pattern:

x.x.x.x   var1:var2
y.y.y.y   var3:var4

What I tried is:

#!/bin/bash

NmapResult=$1

rm oooo
while read line
do
    if [[ "$line" == *Nmap* ]]; then
        OUT=$(grep "Nmap" -A6)
        if [[ "$OUT" == *valid* ]]; then
            continue
        else
            grep "Nmap" -A6 >> oooo
            echo
        fi
    fi
done < $NmapResult

But this is not true and not exactly what I want.

Could you possibly help me on this thread?

Thanks


Solution

  • $ awk -v RS= -F'\n' '{n=split($1,a,/ /); sub(/\| */,"",$7); print a[n], $7}' file
    x.x.x.x var1:var2
    y.y.y.y var3:var4
    z.z.z.z No valid accounts found
    

    or if you want to exclude the 3rd line of output, you might want:

    $ awk -v RS= -F'\n' '$7~/:/{n=split($1,a,/ /); sub(/\| */,"",$7); print a[n], $7}' file
    x.x.x.x var1:var2
    y.y.y.y var3:var4