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


should become


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


In this simple case, you could try

sed 's,(bar,(/foo/bar,'
  • 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

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

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

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

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.


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.


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.