Replace a string in shell script using a variable

后端 未结 10 1197
被撕碎了的回忆
被撕碎了的回忆 2020-11-22 05:18

I am using the below code for replacing a string inside a shell script.

echo $LINE | sed -e \'s/12345678/\"$replace\"/g\'

but it\'s getting

10条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 05:53

    To let your shell expand the variable, you need to use double-quotes like

    sed -i "s#12345678#$replace#g" file.txt
    

    This will break if $replace contain special sed characters (#, \). But you can preprocess $replace to quote them:

    replace_quoted=$(printf '%s' "$replace" | sed 's/[#\]/\\\0/g')
    sed -i "s#12345678#$replace_quoted#g" file.txt
    

提交回复
热议问题