sed substitution with bash variables

这一生的挚爱 提交于 2019-12-11 14:27:33

问题


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?


回答1:


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



回答2:


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!!




回答3:


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

would this work?




回答4:


You can use variables like below. Like here, i wanted to replace hostname ie, system variable in file. I am looking for string look.me and replacing that whole line with look.me=<system_name>

sed -i "s/.*look.me.*/look.me=`hostname`/"

You can also store your system value in other variable and can use that variable for substitution.

host_var=`hostname`

sed -i "s/.*look.me.*/look.me=$host_var/"


Input file :

look.me=demonic

Output of file (assuming my system name is prod-cfm-frontend-1-usa-central-1 ) :

look.me=prod-cfm-frontend-1-usa-central-1


来源:https://stackoverflow.com/questions/49813321/find-and-replace-text-in-json-with-sed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!