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.
6
Answers
I don’t think you’re using a version of
awk
that supportsFPAT
. But even if it did, it wouldn’t do what you seem to expect.Instead, start by using quotes as the field separators. Then the string
dns1,68.6.16.30,35
will be field 2. You can then usesplit()
to split this at comma delimiters.This solution doesn’t require any GNU extensions, these are all POSIX features.
Assuming you need these values inside a shell loop for some reason, this might be what you want, using any awk:
I’m using lower case variable names for the reasons described at Correct Bash and shell script variable capitalization.
As you already drive this via a script just use read to parse each line:
and example run:
As bash is tagged, you can also use regular expressions with capture groups, which can be accessed via the
${BASH_REMATCH[@]}
array. A well-composed regex can even be used to only consider lines containingNODE
, replacing your initialgrep
filter:something like …, my two bits ..
If the file is already sourced (or sourcing them won’t be an issue), you can access the variables starting with
NODE
using the Bash parameter expansion${!prefix@}
: