For performance reasons I have to use sed to replace some text in a file and I just can't get it working. This is the search query (that works in C#) to be replaced:


First off I can't seem to correctly escape the / i am using single quotes with double backslash so


And then I get to the problem on how to replace this with a empty string.

sed 's/<oTimer.*?\\/g>

doesn't seem to do it.

  • That sed substitution expression should give you an error message as it does not contain a replacement part.
    – Kusalananda
    Sep 25, 2017 at 9:07

3 Answers 3

  • If <oTimer.*?/> is your regexp, note that <oTimer/>something else <anothertag?> will also match. Is this desired? Maybe you are looking for an html parser instead?

  • Are you sure about the question mark? It has no special meaning in basic regular expressions, so your pattern needs to end in (unusual) ?/>

  • You need a single backslash to escape the slash, but in this case it's easier to read using a different delimiter to your s command (you are free to choose one!): s_regex_replacement with /_

  • If you want to replace with an empty string, you still need the third delimiter (the second and the third surround the replacement string, so for an empty replacement you have two delimiters with nothing in between).

  • In total, I suspect you are looking for something like sed 's_<oTimer[^>]*/>__g'

  • .*? is the non-greedy version of .*. Sep 25, 2017 at 8:18
  • Not in basic regexp.
    – Philippos
    Sep 25, 2017 at 8:19
  • The OP specifically mentioned C#. Sep 25, 2017 at 8:20
  • 1
    He mentions sed, so I explain for sed.
    – Philippos
    Sep 25, 2017 at 8:20
  • 1
    Yup, the OP tries to emulate with sed the effect of C# matching .*?. The problem is valid, his attempt at solving it isn't. Sep 25, 2017 at 8:23

First, sed doesn't support non greedy quantifier *?.

Second, you should change the substitution operator's delimiter:

sed 's~<oTimer[^>]*/>~~g'

Don't use sed for this since it doesn't understand non-greedy matching. You can use perl instead:

perl -pe 's|<oTimer.*?/>||g' file.in > file.out

Or, to edit the file in place:

perl -i.bak -pe 's|<oTimer.*?/>||g' file.in

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .