不知何故,以下代码无效。 echo显示正确的命令,但不在文件中进行替换。
文件abcd.txt:
\overviewfalse
\part1false
\part2false
\part3false
\part4false
\part5false
\part6false
\part7false
码:
function convert_to_true()
{
sed -i 's/overviewfalse/overviewtrue/' abcd.txt
for iterator in `seq 1 10`; do
match=part${iterator}false
replace=part${iterator}true
command="sed -i 's/${match}/${replace}/' abcd.txt"
echo $command
$(command)
done
}
使用多个反模式,1)摆脱变量中的shell命令,使用函数或数组。但是根据您的要求,您不需要其中任何一个。 2)单引号不会在任何shell中扩展变量。
只需做支撑扩展逻辑而不是使用非标准的seq
用法,
for iterator in {1..10}; do
match="part${iterator}false"
replace="part${iterator}true"
sed -i "s/${match}/${replace}/" abcd.tex
done
或者为sed
使用all函数,如果你需要一个单独的函数
sed_replace_match() {
(( "$#" >= 2 )) || { printf 'insufficient arguments\n' >&2; }
sed -i "s/${1}/${2}/" abcd.tex
}
并使用搜索和替换模式调用该函数,即
sed_replace_match "$match" "$replace"
或者,如果你只想一次性完成所有操作,只需使用GNU sed并且不要担心数字,因为它们作为捕获组\1
的一部分保留在替换中,如下例所示
sed -r 's/part([0-9]*)false/part\1true/g' abcd.tex
如果内容看起来很好,请使用-i
选项进行文件的就地编辑。或者任何符合POSIX标准的sed
都可以使用
sed 's/part\([0-9]*\)false/part\1true/' file