0

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
tripleee
  • 175,061
  • 34
  • 275
  • 318
  • See https://mywiki.wooledge.org/BashFAQ/001 – KamilCuk Nov 16 '21 at 09:58
  • Copy/paste your script into http://shellcheck.net, fix the issues it tells you about, and also read [why-is-using-a-shell-loop-to-process-text-considered-bad-practice](https://unix.stackexchange.com/questions/169716/why-is-using-a-shell-loop-to-process-text-considered-bad-practice) as you probably have the wrong approach to your problem. – Ed Morton Nov 16 '21 at 22:02
  • 1
    @EdMorton very useful website! good to know! Thanks a lot! – Hanhan lee Nov 17 '21 at 01:58

1 Answers1

1

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).

tripleee
  • 175,061
  • 34
  • 275
  • 318