我有一个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
答案 0 :(得分:3)
在AWK函数sub
中替换一个/第一个实例。如果将sub
替换为gsub
,则应替换所有实例。因此,这应该可行:
sig=2.6
awk -v sig="$sig" '{
gsub(/XSIGX/, sig);
print;
}' input.txt > output.txt