2

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:

  • personA has {neta netb netc} items in his bag
  • personB has {meta metb metc metd} items in his bag

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.