1

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:

<oTimer.*?/>

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

<oTimer.*?\\/>

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.

1
  • 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

2
  • 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'

7
  • .*? 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
1

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

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

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

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

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.