简体   繁体   中英

sed command to replace string

I was trying to replace %2$u with

 <ph name='NUMBER' ex='%2$u'/>

across multiple files using the following command.

find . -name "*.txt" -print | xargs sed -i 's/%2$u/<ph name='NUMBER' ex='%2$u'\/>/g'

And actually %2$u is getting replaced like this

<ph name=NUMBER ex=%2/>

Can someone give me the solution? Thanks in advance.

-Ranjit

You cannot embed a single quote inside a single quoted string. Try:

find . -name "*.txt" -print |
  xargs sed -i 's/%2$u/<ph name='"'"'NUMBER'"'"' ex='"'"'%2$u'"'"'\/>/g'

or

find . -name "*.txt" -print |
    xargs sed -i "s/%2\$u/<ph name='NUMBER' ex='%2\$u'\/>/g"

Depending on the version of sed, you may need to escape the $ to sed to prevent it from only matching end of line:

xargs sed -i "s/%2\\\$u/<ph name='NUMBER' ex='%2\\\$u'\/>/g"

When quoting with single quotes , the very next single quote ends the quoting. So the latter expression actually consists of these parts:

's/%2$u/<ph name='
NUMBER
' ex='
%2$u
'\/>/g'

And within the unquoted parts, parameter expansion takes place. So $u is getting replaced by the value of the parameter u , or the empty string, if not existing. You can test this with a simple echo :

echo 's/%2$u/<ph name='NUMBER' ex='%2$u'\/>/g'

To avoid this, either use different quoting technique, eg double quotes for the parts containing single quotes (remember to escape the $ in it, otherwise expansion takes place):

's/%2$u/<ph name='"'NUMBER'"' ex='"'%2\$u'"'\/>/g'

Or use double quotes within the replaced string, if applicable:

's/%2$u/<ph name="NUMBER" ex="%2$u"\/>/g'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM