user466130
user466130

Reputation: 367

how to assign multiple field into a variable?

i would like to convert the data.txt file into the following output using awk 1liner

cat data.txt

  • personA neta netb netc
  • personB meta metb metc metd

....

output:

Upvotes: 2

Views: 773

Answers (4)

glenn jackman
glenn jackman

Reputation: 247002

while read line; do
  set -- $line
  person=$1
  shift
  printf "%s has {$s} items in his bag" "$person" "$*"
done < data.txt

Upvotes: 1

matchew
matchew

Reputation: 19655

this is a good use for subtr() and index().

awk '{print $1FS"has {"substr($0,index($0,$2))"} itmes in his bag."}' data.txt

output:

personA has {neta netb netc} itmes in his bag.

personB has {meta metb metc metd} itmes in his bag.

Upvotes: 2

Vaughn Cato
Vaughn Cato

Reputation: 64308

awk '{$1=$1" has";$2="{"$2;print $0"} items in his bag"}' data.txt

Upvotes: 1

imm
imm

Reputation: 5919

What about:

awk '{ items=""; 
       for(i=2;i<=NF;i++) {items=items" "$i}; 
       gsub(/^[ ]/, "", items);
       print $1" has {"items"} items in his bag" }' data.txt

Upvotes: 0

Related Questions