Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

awk replace all occurrences of a string globally

I have a bash script that substitutes strings in another file:

...
# make MC input script
sig=2.6
awk -v sig="$sig" '{
        sub(/XSIGX/, sig);
        print;  

}' input.txt > output.txt

When I run this on input.txt I get the following as output.txt (notice replacements as "2.6" but the lack thereof in the cat line):

...
echo "hi" >> /work/d/dfranz/o2_modeling/simulated_densities_2.6.txt

cat /work/d/dfranz/o2_modeling/simulated_densities_2.6.txt | sort -nk1 > /work/d/dfranz/o2_modeling/simulated_rho_sorted_XSIGX.txt  # <--- This XSIGX was not replaced but the first occurrence in this line was
rm /work/d/dfranz/o2_modeling/simulated_densities_2.6.txt
like image 531
khaverim Avatar asked Feb 03 '17 20:02

khaverim


1 Answers

In AWK function sub replaces one/first instance. If you replace sub with gsub should replace all instances. Hence this should work ok:

sig=2.6
awk -v sig="$sig" '{
        gsub(/XSIGX/, sig);
        print;  

}' input.txt > output.txt
like image 115
George Vasiliou Avatar answered Oct 22 '22 04:10

George Vasiliou