Home > Back-end >  Replace Proxy Credentials with sed
Replace Proxy Credentials with sed

Time:08-04

I try to replace this samples:

http_proxy="http://[email protected]:8080/"
http://test1:[email protected]:8080/
http_proxy="http://[email protected]:8080/
http://@127.0.0.1:8080/"

with this regex (^. ?\/\/). ?(@.*$) to get it like this

http_proxy="http://user:[email protected]:8080/"
http://user:[email protected]:8080/
http_proxy="http://user:[email protected]:8080/"
http://user:[email protected]:8080/

According to https://regex101.com/r/AE3Wxi/3 the regex seems to be working for the first 3 lines.

But when i try it with

echo http_proxy=\"http://[email protected]:8080/\" | sed  's/\(^. ?\/\/\). ?\(@.*$\)/\1user:pass\2/g'

It has this output:

http_proxy="http://[email protected]:8080/"

CodePudding user response:

You have to escape the plus \ and sed does not support non greedy quantifiers like .\ ?

If you also want a match for the last example http://@127.0.0.1:8080/" the quantifier after the double forward slash should be * instead of

You could write the command as:

echo http_proxy=\"http://[email protected]:8080/\" | sed  's/\(^.\ \/\/\).*\(@.*$\)/\1user:pass\2/'

Output

http_proxy="http://user:[email protected]:8080/"

If you only want to replace the first occurrence in the line, you might shorten it to

echo http_proxy=\"http://[email protected]:8080/\" | sed  's~\(//\)[^@]*\(@\)~\1user:pass\2~'

See a regex demo and here for the captured group values.

  • Related