0

Sorry if this has been asked before, but I haven't found anything so far.

Here's the thing: I have a string and a pattern, and want to surround the pattern inside the string with brackets.

While I want to surround the pattern regardless if it has been matched case-sensitively or not, I want to have it in the same case as it was in the original string.

Here's my best try so far:

#!/bin/bash

STRING="ABCBD"
PATTERN="b"

echo $STRING | sed "s/$PATTERN/[$PATTERN]/Ig"

The output for this is A[b]C[b]D. However, I would like it to be A[B]C[B]D.

If the pattern was B instead of b, the output should also be A[B]C[B]D.

If the string was abcbd instead of ABCBD, the output should be a[b]c[b]d for both patterns B or b.

Do you know any tricks to achieve this? I am glad for any help.

0

You can do it with sed as well.

echo $STRING | sed -e "s/\($PATTERN\)/[\1]/Ig"
0

If you don't mind Perl, it's:

echo $STRING | perl -pe "s/($PATTERN)/[\1]/ig"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.