Replace an expression with special characters by another in shell script or sed [duplicate]

淺唱寂寞╮ 提交于 2019-12-12 06:48:40

问题


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 variable old to sed.
  • Let me write the sed command in an expanded form: sed -r 's/ [*] / \\* /g'
    • -r because we are using regex in pattern to match.
    • [*] is the regex 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 variable old.


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

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