Replace string in another file with sed from bash script
I'm trying to replace the value of an environment variable definition, if it exists, from a bash script. I know I can use sed
to do this, I'm not sure, however, how to replace the value of the environment var开发者_运维百科iable?
Here's what I'd like to do:
Given a file with this line (found with grep
):
export MY_ENV=SOME_VALUE
I'd like to replace SOME_VALUE
with something else. How do I do that with sed
?
This searches for the line beginning with export MY_ENV=
and substitutes the rest of the line with NEW_VALUE
:
sed 's/^\(export MY_ENV=\).*$/\1NEW_VALUE/'
sed -e "s/SOME_VALUE/$MY_ENV/"
This locates the string SOME_VALUE
and substitutes the value of $MY_ENV
. The double quotes are crucial; don't use single quotes unless you want $
, M
, Y
, ... in the replacement text.
精彩评论