-1

I have written a bash script (File.sh) to change the third column of a file (File.txt) with a particular string (NULL).

File.txt -

abc def 123
qwe gfh 456

File.sh -

#!/bin/bash
FILE1='file.txt'
while IFS= read -r line
do
    awk '$3= "NULL"' file.txt > tmp.txt && mv tmp.txt file.txt
done <"$FILE1"

and this works fine.

output

abc def NULL
qwe gfh NULL

But now I'am trying to update the third column using a variable instead of a text-

var='NULL'
awk '$3= $var' file.txt > tmp.txt && mv tmp.txt file.txt

this doesn't work. what can be the mistake in syntax.

Suchin Raj
  • 17
  • 2
  • 8
  • 1
    You have taken an O(n) operation and made it O(n^2). For each line in the file, you are going through the entire file and changing the entry in the 3rd column. Don't do that. – William Pursell Jun 12 '18 at 14:37

1 Answers1

0

Could you please try following.

var="NULL"
awk -v var="$var" '{$3=var} 1' Input_file > temp_file && mv temp_file Input_fle
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93