在sed中使用变量

信息阻塞

以下代码无法正常工作。回显显示正确的命令,但不会在文件中进行替换。

文件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如果您根本需要单独的功能

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章