khaverim
khaverim

Reputation: 3554

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

Upvotes: 9

Views: 9614

Answers (1)

George Vasiliou
George Vasiliou

Reputation: 6345

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

Upvotes: 13

Related Questions