adding a line to a text file

I have a tab delimited text file,

id   name       distance
1    3325167    0.334561754018
2    3290488    0.389444269458
3    3288794    0.392312701782
4    3347602    0.392532202097
5    3295355    0.394394169485

I need to add a line after the header line. The first and third field of that added line with both be the value 0 (hard coded). The middle field will be from a bash variable.

id   name       distance
0    $BASH_VAR  0.0
1    3325167    0.334561754018
2    3290488    0.389444269458
3    3288794    0.392312701782
4    3347602    0.392532202097
5    3295355    0.394394169485

I have looked at solutions in both sed and awk and can't seem to find the right thing.

I tried,

awk 'BEGIN {FS="\t"} {if (NR==2) print "0", "\t", $NAME, "\t", "0.0"; else print $0; }' TEMP > $OUTFILE

But that garbles the values of the inserted and existing lines.

LMHmedchem

% BASH_VAR=hello 

% cat testfile   
id   name       distance
1    3325167    0.334561754018
2    3290488    0.389444269458
3    3288794    0.392312701782
4    3347602    0.392532202097
5    3295355    0.394394169485

% sed '1a\       
0    '$BASH_VAR'  0.0' testfile
id   name       distance
0    hello  0.0
1    3325167    0.334561754018
2    3290488    0.389444269458
3    3288794    0.392312701782
4    3347602    0.392532202097
5    3295355    0.394394169485

If you need right columns try:

BASH_VAR=`printf '%-9s' hello`
1 Like

I need tab delimited, so I got it to work with,

sed '1a\0\t'$BASH_VAR'\t0.0' TEMP > $OUTFILE

what is the meaning of the 1a\ notation? Does that mean to add the line at position 1? I thought you generally needed double quotes to preserve the value of the $VAR.

LMHmedchem

Yes.

Here it can work, but it won't in common case because sed and shell metachars can conflict (especially backslashes). So usual practice to embed shell variables in sed command is:

sed '...'$VAR'...'

Sorry for my English.