Search code examples
outputlines

Lines with common words in outputs of 2 scripts


I need to run two linux shell scripts and get lines from the second script that contain same words as lines in the output from the first (not the whole line is the same). For example:

Script #1 output:
Router 1: Ip address 10.0.0.1
Router 2: Ip address 10.0.1.1
Router 3: Ip address 10.0.2.1

Script #2 output:
Router 1: Model: Cisco 2960
Router 2: Model: Juniper MX960
Router 5: Model: Huwei S3300

So, finally I need a list of routers that are present in both outputs, but only lines from the second script, i.e. lines with model.


Solution

  • Considering the above two script output is stored/redirected to tmp1 and tmp2 respectively.

    Below script will output the common Router X present in both the files.

    #!/bin/bash
    tmp1="$1"
    tmp2="$2"
    while read -r line
       do   
        routerName=$(echo "$line" | cut -d ":" -f 1)
        if grep -q "$routerName" "$tmp2"
           then
            # Instead of printing you can add any logic
            echo $routerName
        fi
    done < "$tmp1"
    

    save the above script as filename.sh and pass the arguments

    ./filename.sh tmpScript1output_file tmpScript2output_file