I have the following pattern on a few thousand lines I will like to use regex to convert to what I want

RewriteRule ^/omg/deadly-venom/?$ http://www.example.com/omg/deadly-venom [L,NC,R=301]
RewriteRule ^/buzz/get-on-it/?$ http://www.example.com/buzz/get-on-it/ [L,NC,R=301]

and others like this for a few thousand lines

So basically I want to have this

RewriteRule ^/omg/(deadly-venom)/?$ http://www.example.com/omg/$1 [L,NC,R=301]
RewriteRule ^/buzz/(get-on-it)/?$ http://www.example.com/buzz/$1 [L,NC,R=301]

How do I achieve this? I use the sublime text editor but can also use sed or awk in terminal.

UPDATED: the last / should not result in double slash before the $1 like this //$1 instead it should still be /$1 just look at the before and after from above and see lines with ending / and the one without

  • Looks like a simple sed 's/ [/$1 [/' might work...
    – Jeff Schaller
    Mar 11, 2016 at 21:55
  • not working..you sure thats the correct syntax? also can you add as answer instead of comment? thanks
    – uberrebu
    Mar 11, 2016 at 22:03

1 Answer 1


I'd do it like this:

sed -E 's|(.*/)([^/]*)(/\?\$.*)\2/{,1}|\1(\2)\3$1|' infile

The 2nd group captures the string/pattern that has to be enclosed in (...), the 3rd group captures everything that follows up to the same string (backreferenced with \2 in the LHS) which may have a trailing slash. So, basically, this replaces \1\2\3\2{0 or 1 slash} with \1(\2)\3$1.
If your sed doesn't support extended regex via -E:

sed 's|\(.*/\)\([^/]*\)\(/?\$.*\)\2/\{,1\}|\1(\2)\3$1|' infile

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.