问题
In a file x
, a line containing 4*4 4*1 4*4 4*0
is to be replaced by 4*4 4*1 3*4 1*4 4*0
which is in file y
. I'm using the following code:
#!/bin/bash
old=`grep "4*4" x`;
new=`grep "4*4" y`;
sed -i "s/${old}/${new}/g" x
but it yields no change at all in x
. I'm a novice and this might be a silly question for this site but I'm unable to replace this expression with multiple special characters with another expression.
回答1:
Welcome to stackOverflow - An awesome platform for developers 😃
If you stick around, you will also find it very rewarding. 🙂
Now to your question.
*
is a special character for sed
when it is included in pattern to match. More info here.
Thus, we need to escape it with a \
.
You can use something like old=$(echo "${old}" | sed -r 's/[*]/\\*/g')
to do so for each *
inside variable old
.
echo "${old}" |
feeds the value of variableold
tosed
.- Let me write the
sed
command in an expanded form:sed -r
's/
[*]
/
\\*
/g'
-r
because we are usingregex
in pattern to match.[*]
is theregex
and also the pattern to match. Info\\*
is the replacement string - The first\
is escaping the second\
and*
is being treated as a normal character.
$( )
has been used to assign the final output to variableold
.
Here is the modified script:
#!/bin/bash
# Read the strings
old=`grep "4*4" x`;
new=`grep "4*4" y`;
# Escape * i.e. add \ before it - As * is a special character for sed
old=$(echo "${old}" | sed -r 's/[*]/\\*/g')
# Replace
sed -i "s/${old}/${new}/g" x
来源:https://stackoverflow.com/questions/52628567/replace-an-expression-with-special-characters-by-another-in-shell-script-or-sed