Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace Proxy Credentials with sed

I try to replace this samples:

http_proxy="http://QQ@127.0.0.1:8080/"
http://test1:test2@127.0.0.1:8080/
http_proxy="http://QQ@127.0.0.1:8080/
http://@127.0.0.1:8080/"

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

http_proxy="http://user:pass@127.0.0.1:8080/"
http://user:pass@127.0.0.1:8080/
http_proxy="http://user:pass@127.0.0.1:8080/"
http://user:pass@127.0.0.1:8080/

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

But when i try it with

echo http_proxy=\"http://QQ@127.0.0.1:8080/\" | sed  's/\(^.+?\/\/\).+?\(@.*$\)/\1user:pass\2/g'

It has this output:

http_proxy="http://QQ@127.0.0.1:8080/"

>Solution :

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://QQ@127.0.0.1:8080/\" | sed  's/\(^.\+\/\/\).*\(@.*$\)/\1user:pass\2/'

Output

http_proxy="http://user:pass@127.0.0.1:8080/"

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

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

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading