awk全局替换所有出现的字符串

时间:2017-02-03 20:05:07

标签: string bash awk replace

我有一个bash脚本替换另一个文件中的字符串:

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

}' input.txt > output.txt

当我在input.txt上运行时,我得到以下output.txt(请注意替换为" 2.6"但缺少cat行:

...
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

1 个答案:

答案 0 :(得分:3)

在AWK函数sub中替换一个/第一个实例。如果将sub替换为gsub,则应替换所有实例。因此,这应该可行:

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

}' input.txt > output.txt