Home > Enterprise >  Escape slashes in capture groups in sed
Escape slashes in capture groups in sed

Time:05-18

My input (from Jenkins) goes under the second %s parameter and some of it contains slashes.

I would like to replace / with \/, not sure where and how I can do it

'''sed -i -e 's/^\\(%s[ ]*=[ ]*\\)\\(.*\\)/\\1%s/' "%s/file/%s"'''

My guess it should be inside the second parenthesis \\(.*\\)? How can I express the replace / with \/?

I know I can use another sed delimiter but I would also like to understand whether and how it is possible to manipulate input with capture groups and regex

CodePudding user response:

If you use / as the substitute delimiter, then it's a special character and needs to be escaped yielding \/ The backslash is already a meta character and needs to be escaped to be treated literally yielding \\. Putting it together:

s/\//\\\//g

will replace all slashes with \/.

It will be easier to read if you use another delimiter:

s:/:\\/:g

CodePudding user response:

Using sed

$ echo "s3://bucket/folder/text.txt" | sed s'|\(/\)|\\\1|g'
s3:\/\/bucket\/folder\/text.txt
  • Related