hbaromega hbaromega - 1 year ago 88
Bash Question

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.


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
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
, which I don't want. Any help?

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

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download