Regex:search/replace but not for escaped character

Hi

Input:

-
--
---
----
aa-bb-cc
aa--bb--cc
aa---bb---cc
aa----bb----cc

Output:

.
-
-.
--
aa.bb.cc
aa-bb-cc
aa-.bb-.cc
aa--bb--cc

I need to replace a simple '-' with '.' but if I want to keep the '-' I will use '--'

I would a like a solution where regex is used as search criteria and the match will be replace with a value. A solution that can be used in language.

Thx in advance

This is a three step process:

  1. Convert all occurrences of -- to something that doesn't appear in your input.
  2. Convert all remaining occurrences of - to . .
  3. Convert all of the characters you converted to in step 1 back to - .

The way you do this "in language" depends on what language you want to use.

1 Like

Here is how Don Cragun suggested using sed

sed 's/\-\-/\%/g' | sed 's/\-/\./g' | sed 's/\%/\-/g'

Great solution. Thx

Yes; or more succinctly in sed:

sed -e 's/\-\-/\%/g' -e 's/\-/\./g' -e 's/\%/\-/g'

or even

sed 's/\-\-/\%/g;s/\-/\./g;s/\%/\-/g'

or in awk:

awk '{gsub(/--/,"%");gsub(/-/,".");gsub(/%/,"-");print}'

but there are LOTS of languages. Why don't we let the submitter tell us what language he wants.

That's a lot of unnecessary and undefined escape sequences (which are typically treated by pretending the backslash wasn't there):

sed 's/--/%/g; s/-/./g; s/%/-/g'

Regards,
Alister

1 Like

Yes, absolutely. I copied from the wrong place when I created my last post. Thank you alister for pointing out my mistake.

  • Don

The language is not important but defining the steps like you suggested