0

I would like to replace a string with another string. For example: I would like to change the following text:

"listen_addresses = ['127.0.0.1:53', '[::1]:53']"

to the following text

"listen_addresses = ['127.0.0.1:40', '[::1]:40']"

I tried this command:

sudo sed "s#listen_addresses \= \['127\.0\.0\.1\:53'\, '\[\:\:1\]\:53'\]'#listen_addresses \= \['127\.0\.0\.1\:40'\, '\[\:\:1\]\:40'\]#g"

and I got this result:

input: listen_addresses = ['127.0.0.1:53', '[::1]:53']

output: listen_addresses = ['127.0.0.1:53', '[::1]:53']

What am I doing wrong?

  • you only need to escape [ and ], and in first part of replacement. – Archemar Sep 3 '18 at 12:17
  • 3
    You're not "replacing any string", you're replacing a very specific string -- the port at the end of a listen_address configuration list in a file. Understanding exactly what you want leads people a long way towards the correct answer. – Jeff Schaller Sep 3 '18 at 12:20
1

as explain in comment, only [ and ] are to be escaped

echo "listen_addresses = ['127.0.0.1:53', '[::1]:53']" |
sed -e "s#listen_addresses = \['127.0.0.1:53', '\[::1\]:53'#listen_addresses = ['127.0.0.1:40', '[::1]:40'#"

which give

listen_addresses = ['127.0.0.1:40', '[::1]:40']
0

You can do:

sed "/^listen_addresses = \['127\.0\.0\.1:53', '\[::1\]:53'\]$/s/53/40/g" file

  • Searches for the exact string listen_addresses = ['127.0.0.1:53', '[::1]:53']
  • If the string matches s/53/40/g will replace all occurences of 53 with 40 (but only in the matched line)

Example output:

$ cat file
listen_addresses = ['127.0.0.1:53', '[::1]:53']
listen_addresses = ['127.0.0.2:53', '[::1]:53']

$ sed "/^listen_addresses = \['127\.0\.0\.1:53', '\[::1\]:53'\]$/s/53/40/g" file
listen_addresses = ['127.0.0.1:40', '[::1]:40']
listen_addresses = ['127.0.0.2:53', '[::1]:53']

As you can see, an exact match is needed to perform the replace.

0
sed s/":53'"/":40'"/g <<<"listen_addresses = ['127.0.0.1:53', '[::1]:53']"

do something close to you asked. But I agree with comment of @Jeff Schaller!

From your question nobody can recognize why do you simply do not it by hand? What is the text from which you get your lines, how they differs each other? what variants should be covered by regex?

sed is good for replacing but for electing the coresct line the grep is better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.