user959129
user959129

Reputation:

find and replace in a text file using sed

I am new to sed.

I have a text file and I want to replace the occurrence of this string:

allow ^127\.0\.0\.1$

with this string:

allow ^107\.21\.206\.35$

the code I used was the following:

sed 's/allow ^127\.0\.0\.1$/allow ^107\.21\.206\.35$/g' test.txt

However, id did not work. What did I do wrong?

Thanks

Upvotes: 1

Views: 1087

Answers (3)

potong
potong

Reputation: 58351

This might work for you:

echo 'allow ^127\.0\.0\.1$' | 
sed 's/allow ^127\\.0\\.0\\.1\$/allow ^107\\.21\\.206\\.35$/'
allow ^107\.21\.206\.35$

The ^ and $ only need to be escaped in the match part of the substitution command if they are at the front and back of a string respectively. The \ needs to be escaped in both the match and the replacement.

Upvotes: 0

Andy
Andy

Reputation: 17771

You should escape not only the \ (with another backslash) but also the . (Regular Expressions treat . as "match any single character"). The ^ and $ characters are also reserved in Regular Expressions.

$ echo "allow ^127\.0\.0\.1$" > /tmp/test
$ cat /tmp/test
allow ^127\.0\.0\.1$
$ sed 's/allow \^127\\\.0\\\.0\\\.1\$/allow ^107\\.21\\.206\\.35$/g' -i /tmp/test
$ cat /tmp/test
allow ^107.21.206.35$

In the replace string, the \ should be escaped otherwise the single \ will escape the . next to it.

Upvotes: 0

William Pursell
William Pursell

Reputation: 212168

You must escape '^' and '$':

$ sed 's/allow \^127\.0\.0\.1\$/allow \^107\.21\.206\.35\$/g' test.txt

Unescaped, the '^' matches the beginning of the line, and '$' matches the end of line. In order to match the character exactly, they must be escaped with '\'. Most implementation of sed use basic regular expressions in which the following characters must be escaped to match literally: ^.[$()|*+?{\

Upvotes: 1

Related Questions