hbaromega hbaromega - 2 months ago 13
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.

#!/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. Any help?

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?

Answer

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
}'
Comments