I have a problem with sed
unable to correctly capture the \1
capture group in the below example:
echo '//apple' | sed "s/^\(\/\)\{0,2\}apple\(\/\)\?/\1banana\2/"
------------- --
^ ^
| |__ writing back what it captured
|
|_ this is the capture group that I have problem capturing
I expected the output of: //banana
correctly capturing the //
. How can I make sed
to correctly the \1
capture group?
CodePudding user response:
You only captured one /
.
You need to use
echo '//apple' | sed 's/^\(\/\{0,2\}\)apple\(\/\)\?/\1banana\2/' # POSIX BRE
echo '//apple' | sed -E 's~^(/{0,2})apple(/)?~\1banana\2~' # POSIX ERE variant
CodePudding user response:
With an alternate delimiter and -E
use cleaner and easier to read:
echo '//apple' | sed -E 's~^(/{0,2})apple(/{0,2})~\1banana\2~'