1

I have this sed command for deleting numbers inside of tags:

sed 's/\(<[^0-9>]*\)[0-9]*\([^0-9]*>\)/\1\2/g'

But does anyone know how I can exclude certain strings from this?

Now it would so something like this, input:

<user1></user1>
<password2></password2>

And output:

<user></user>
<password></password>

However, I want to be able to exclude certain strings, like password2 for example, then the output would be like this:

<user></user>
<password2></password2>
  • @AaronD.Marasco, there's a tacit rule on U&L that before posting a link to that SO Q&A, you must answer the question without using a regex. – Stéphane Chazelas Dec 20 '15 at 23:44
  • @AaronD.Marasco I have seen that many times, it's such a stupid answer. It doesn't say why you shouldn't parse it with regex, just "don't parse it with regex". – DisplayName Dec 20 '15 at 23:48
  • 1
    @DisplayName read any of the other highly voted answers for better explanations of why you shouldn't do it. Alternatively, have look at this example of how to do it correctly. Unless you can write something like that, avoid parsing anything except the most simple HTML with regular expressions. – terdon Dec 21 '15 at 9:25
1

You could preprocess your file to insert a special character for those strings you want to whitelist to prevent them for being replaced.

Like you'd change:

<user1></user1>
<password2></password2>

To

<user1></user1>
<|password2><|/password2>

first and use s/\(<[^|0-9>]*\)[0-9]*\([^0-9]*>\)/\1\2/g for the substitution. If | may already occur in the input, you can escape them using a scheme like: _ -> _u, | -> _p which you'd undo afterwards.

sed '
  s/_/_u/g;s/|/_p/g
  s:<\(/\{0,1\}password2>\):<|\1:g
  s:<\(/\{0,1\}othertag>\):<|\1:g
  s/\(<[^|0-9>]*\)[0-9]*\([^0-9]*>\)/\1\2/g
  s/|//g;s/_p/|/g;s/_u/_/g'

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.