Aeris
Aeris

Reputation: 347

SED escape special characters

I'm trying to use SED and change a line in a file:

 "homepage": "http://localhost:123/",

to

 "homepage": "http://localhost:123/newpath",

using

sed -i "s/^"homepage": "http:\/\/localhost:123\/"/"homepage": "http:\/\/localhost:123\/newpath"/g"

But it doesnt work, maybe i forgot to escape?

Edit: Plus there is another nearly similiar line in the file (which should not be modefied)!

"proxy": "http://localhost:123",

Upvotes: 2

Views: 322

Answers (3)

sjsam
sjsam

Reputation: 21965

$ cat 48308267
"homepage": "http://localhost:123/",<br>
"proxy": "http://localhost:123",
$ sed -i '/^[[:blank:]]*"homepage"/s#:123/#:123/newpath#' 48308267
# the -i option writes the changes to the file itself
$ cat 48308267
"homepage": "http://localhost:123/newpath",<br>
"proxy": "http://localhost:123",

A more generalized version would be to reuse matched patterns

$ cat 48308267
"homepage": "http://localhost:123/",<br>
"proxy": "http://localhost:123",
$ sed -iE '/^[[:blank:]]*"homepage"/s#(:[[:digit:]]+/)#\1newpath#' 48308267
$ cat 48308267
"homepage": "http://localhost:123/newpath",<br>
"proxy": "http://localhost:123",

Note: The general version would work for any port number, not just 123


You have the leverage to change the delimiter of the s command from the default / to virtually anything that doesn't conflict with the pattern.

All good :-)

Upvotes: 2

Bach Lien
Bach Lien

Reputation: 1060

echo '"abc": "http://localhost:123/",<br>' | \
  sed 's|"abc": "http://localhost:123/",<br>|"abc": "http://localhost:123/newpath",|'

sed accepts other delimiters, like :, |, etc.; not only /.

Upvotes: 1

RavinderSingh13
RavinderSingh13

Reputation: 133760

Following simple sed may help you in same.

sed 's/",$/newpath",/g'  Input_file

Output will be as follows.

"abc": "http://localhost:123/newpath",

If you are happy with above code's output into same Input_file itself then add -i option with sed too.

Upvotes: 0

Related Questions