0

How could I insert /foo/ after and only after opening brackets?

(bar)

should become

(/foo/bar)

while (/baz/bar) should not become (/baz/foo/bar)

0
5

In this simple case, you could try

sed 's,(bar,(/foo/bar,'
2
  • Wouldn't this harcode bar? Though the question is not that clear if that's what is wanted. May 27 at 12:19
  • @schrodigerscatcuriosity You are right, but I assumed from the example ("(/baz/bar) should not become (/baz/foo/bar)") that the actual task was to prepend /foo/ to the previously-known fixed string bar, with the boundary condition that this should only happen if bar is the first word after the opening (.
    – AdminBee
    May 27 at 12:27
0

A convoluted way, assuming that you want to add /foo/ to any pattern between parenthesis:

$ echo '(bar)' | sed 's;(/*\([^(]*\);(/foo/\1;'
(/foo/bar)

$ echo '(/bar/baz)' | sed 's;(/*\([^(]*\);(/foo/\1;'
(/foo/bar/baz)

The command says:

Select what is between parenthesis and capture it, (could begin with a slash /), and replace ( or (/ with /foo/ and the captured pattern.

0

Using awk:

awk '/\(bar/ {sub(/bar/, "/foo/bar"); }1' input

With sed:

sed -E 's%([(])(bar)%\1/foo/\2%' input

This uses backreferences \1 for ( and \2 for bar.

0

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.