Skip to main content
added 129 characters in body
Source Link
Ed Morton
  • 35.9k
  • 6
  • 25
  • 60

The right approach is to just call awk once with the list of IPs, create an array of tags/names to values (f[] below) and just access the values by their names. No shell loop (which would be extremely slow), and no getlines (see http://awk.freeshell.org/AllAboutGetline for why those are usually best avoided) required:

The right approach is to just call awk once with the list of IPs. No shell loop, and no getlines (see http://awk.freeshell.org/AllAboutGetline for why those are usually best avoided) required:

The right approach is to just call awk once with the list of IPs, create an array of tags/names to values (f[] below) and just access the values by their names. No shell loop (which would be extremely slow), and no getlines (see http://awk.freeshell.org/AllAboutGetline for why those are usually best avoided) required:

Source Link
Ed Morton
  • 35.9k
  • 6
  • 25
  • 60

The right approach is to just call awk once with the list of IPs. No shell loop, and no getlines (see http://awk.freeshell.org/AllAboutGetline for why those are usually best avoided) required:

$ cat tst.sh
#!/bin/env bash

declare -a iplist=(
    '192.168.0.10'
    '192.168.0.20'
    '192.168.0.30'
    '999.999.999.999'
)

awk -v iplist="${iplist[*]}" '
    BEGIN {
        split(iplist,tmp)
        for (idx in tmp) {
            ip = tmp[idx]
            cnt[ip] = 0
        }
        OFS = "="
        sep = "-----"
    }
    {
        tag = val = $0
        sub(/=.*/,"",tag)
        sub(/^[^=]+=/,"",val)
        f[tag] = val
    }
    $0 == sep {
        ip = f["ip"]
        if ( ip in cnt ) {
            cnt[ip]++
            print "ip", ip
            print "path", f["path"]
            print sep
        }
        delete f
    }
    END {
        for (ip in cnt) {
            if ( cnt[ip] == 0 ) {
                print "ip", ip " NOT IN CONFIG"
                print sep
            }
        }
    }
' config

.

$ ./tst.sh
ip=192.168.0.10
path=/home/user/D1/test/server1
-----
ip=192.168.0.20
path=/home/user/D1/test/server1
-----
ip=192.168.0.30
path=/home/user/D1/test/server1
-----
ip=999.999.999.999 NOT IN CONFIG
-----

I use tag = val = $0, etc. to separate the tags from their values rather than relying on setting FS="=" since = can appear in UNIX directory or file names and so could appear in a path.