Home > Net >  parse text file using awk and store in two variables
parse text file using awk and store in two variables

Time:11-17

I am trying to parse a file just like:

for NAME in `cat file.txt | grep name | awk '{print $2}'`
do
   echo " $NAME  "
   ......
done

file.txt content:

name John box 2
name Joe box 3
name May box 4

Then it will print:

John
Joe
May 

But now I want to get box number in the meantime, I need to store name and box in two variables, how to do this?

Expected result:

echo "$NAME $BOX"
John 2
Joe 3
May 4

CodePudding user response:

You don't need Awk (or cat!) here at all.

grep '^name' file.txt |
while read -r _ name _ box;
do
   echo " $name $box "
   ......
done

Or, if you just want to print those two fields and not do anything with those variables, simply

awk '/^name/ { print $2, $4 }' file.txt

See also don't read lines with for

More fundamentally, you might want to modify your file format so that the labels don't have to be specified on every line (or if that's really useful, probably use a standard file format which allows for this sort of structure, like JSON or perhaps YAML).

  • Related