sed substitution with bash variables

Trying to change values in a text file using sed in a bash script with the line,

sed 's/draw($prev_number;n_)/draw($number;n_)/g' file.txt > tmp

This will be in a for loop. Not sure why it's not working. Any suggestions?


Variables inside ' don't get substituted in bash. To get string substitution (or interpolation, if you're familiar with perl) you would need to change it to use double quotes " instead of the single quotes:

$ # enclose entire expression in double quotes
$ sed "s/draw($prev_number;n_)/draw($number;n_)/g" file.txt > tmp

$ # or, concatenate strings with only variables inside double quotes
$ # this would restrict expansion to relevant portion
$ # and prevent accidental expansion for !, backticks, etc
$ sed 's/draw('"$prev_number"';n_)/draw('"$number"';n_)/g' file.txt > tmp

$ # variable cannot contain arbitrary characters
$ # see link in further reading section for details
$ a='foo 
bar'
$ echo 'baz' | sed 's/baz/'"$a"'/g'
sed: -e expression #1, char 9: unterminated `s' command


Further Reading:

  • Difference between single and double quotes in Bash
  • Is it possible to escape regex metacharacters reliably with sed
  • Using different delimiters for sed substitute command
  • Unless you need it in a different file you can use the -i flag to change the file in place

  • variables within single quotes are not expanded, within double quotes they are, use double quotes in this case.

    sed "s/draw($prev_number;n_)/draw($number;n_)/g" file.txt > tmp
    

    You could also make it work with eval , but dont do that!!


    sed "s/draw($prev_number;n_)/draw($number;n_)/g" 
    

    这会工作吗?

    链接地址: http://www.djcxy.com/p/47132.html

    上一篇: 在sed中用逗号替换逗号

    下一篇: 用bash变量进行sed替换