bashawk

How to use bash for loop to awk print FPAT string found in quoted variable


I cant figure out the proper FPAT to get each comma separated value. Using bash on Debian 12.5... I have a file PING.cfg with contents:

NODE01="router,10.0.0.1,5"
NODE02="dns1,68.6.16.30,35"
NODE03="dns2,1.1.1.1,35"

Those get used as variables sourced in multiple scripts, I want a script to assign each of the comma separated values to a variable in a for loop, maybe something like this:

for n in `grep NODE PING.cfg`
        do
        NODENAME=$(echo "$n" | awk -v FPAT='"[^"]+"' -F',' '{ print $1 }')
        HOSTIP=$(echo "$n" | awk -v FPAT='"[^"]+"' -F',' '{ print $2 }')
        echo "NODE is $NODENAME and HOSTIP is $HOSTIP"
done

But awk does not seem to be reading inside the quotes with my FPAT pattern, the output for $1 includes the entire variable:

NODE is NODE01="router and HOSTIP is 10.0.0.1

Tried FPAT to specify quotes.


Solution

  • Assuming you need these values inside a shell loop for some reason, this might be what you want, using any awk:

    $ cat tst.sh
    #!/usr/bin/env bash
    
    while read -r nodename hostip rest; do
        printf 'nodename is %s and hostip is %s\n' "$nodename" "$hostip"
    done < <(awk -F'[",]' '/^NODE/{print $2, $3}' PING.cfg)
    

    $ ./tst.sh
    nodename is router and hostip is 10.0.0.1
    nodename is dns1 and hostip is 68.6.16.30
    nodename is dns2 and hostip is 1.1.1.1
    

    I'm using lower case variable names for the reasons described at Correct Bash and shell script variable capitalization.