I have this awk statement that reads a YAML file and outputs a particular value. I need to loop this awk inside a loop where I read a key value from a list of values and pass that key to awk.
The YAML file has this structure:
abc:
NAME: Bob
OCCUPATION: Technician
def:
NAME: Jane
OCCUPATION: Engineer
Say I want to get key abc OCCUPATION value of TECHNICIAN, through googling I managed to construct an awk statement that gives what I want
> awk 'BEGIN{OFS=""} /^[^ ]/{ f=/^abc:/; next } f{ if (sub(/:$/,"")) abc=$2; else print abc,$1 $2}' test.yml| grep "OCCUPATION:" | cut -d':' -f2
Technician
However passing -v option to awk does not seem to give anything if I use this loop:
items="abc,def"
for item in $(echo $items | sed "s/,/ /g");
do
echo $item;
awk -v name="$item" 'BEGIN{OFS=""} /^[^ ]/{ f=/^\name:/; next } f{ if (sub(/:$/,"")) name=$2; else print name,$1 $2}' test.yml| grep "OCCUPATION:" | cut -d':' -f2;
done
I get just the debug echos I set out
abc
def
Where am I going wrong? I thought the variable should be interpreted correctly inside awk?
EDIT: Based on steeldrivers comment I have changed the input a little
items="abc,def"
for item in $(echo $items | sed "s/,/ /g");
do
echo $item;
awk -v name="$item" 'BEGIN{OFS=""} /^[^ ]/{ f=name; next } f{ if (sub(/:$/,"")) name=$2; else print name,$1 $2}' test.yml| grep "OCCUPATION:" | cut -d':' -f2;
done
However now I am getting all values for OCCUPATION printed:
abc
Technician
Engineer
def
Technician
Engineer
I tried to use the ~ operator but I think I am not using it right as it is giving me errors, so I decided to just parse the value directly, but this is giving duplicates :/