hbaromega
hbaromega

Reputation: 2374

Inserting multiple variables on a particular line using awk

I want to insert a few variables (say 3) on a particular line (say 3rd line). I have the following MWE.

#!/bin/sh

echo  > testfile
echo  >> testfile
echo  >> testfile
v1=1; v2=2; v3=3
sed -i "3,3c\ $v1  $v2  $v3" testfile
cat testfile

Can I do this using awk just in one step? I can do

awk -v value=$v1 ' NR==3 {$1=value"\t"}1' testfile > tmp; mv tmp testfile

but that is for one variable. I have to create similar lines for v2 and v3, which I don't want.

PS. In the above example, I used echo three times so that I could use sed/awk up to the 3rd line of empty testfile. Is there a cleverer way of inserting on n-th line?

Upvotes: 1

Views: 308

Answers (2)

wpcarro
wpcarro

Reputation: 1536

You can try this. Use -v to define variables at the shell-level.

awk -v v1="$one" -v v2="$two" -v v3="$three" 'BEGIN{OFS="\t"} {print "\n\n" v1, v2, v3}'

Upvotes: 0

anubhava
anubhava

Reputation: 784948

Using awk you can do this with an empty file:

awk -v OFS="\t" -v n=3 -v v1="$v1" -v v2="$v2" -v v3="$v3" 'BEGIN {
   # print n-1 empty lines
   for (i=1; i<n; i++)
      print ""
   # print v1, v2, v3
   print v1, v2, v3
}'

Upvotes: 1

Related Questions