Using Sed to replace a string with another string?

2019-08-08 01:51发布

问题:

I have tried this:

sed -i 's/'Twas/It certainly was/g' *.txt

any suggestions??

回答1:

Use double quotes

sed -i "s/'Twas/It certainly was/g" *.txt


回答2:

The apostrophe in 'Twas is being interpreted as a close quote (by the shell, not sed), and then the subsequent single quote after /g is being interpreted as an open quote, which cheerfully gobbles all the way to the end of the script (or the command prompt, and then you get the mysterious > that means the shell thinks there's more to come). For this situation,

sed -i "s/'Twas/It certainly was/g" *.txt

should work; however, shell double-quoted strings do a lot of stuff you don't usually want with sed programs. If there were any regexp metacharacters at all in there I'd do instead

sed -i 's/'\''Twas/It certainly was/g' *.txt


回答3:

Try using following

grep -rl "Old string" directoryPath | xargs sed -i 's/oldString/new String/g'

Example :

grep -rl 10.113.1.115 matchdir | xargs sed -i 's/10.113.1.115/10.113.1.65/g'