anotheruser anotheruser - 5 months ago 70
Bash Question

match multiple conditions with sed

I'm using sed to replace values in other bash scripts, such as:

somedata=`sed 's/ ==/==/g' <<< $somedata` # [space]== becomes ==
somedata=`sed 's/== /==/g' <<< $somedata` # ==[space] becomes ==

The same for ||, &&, !=, etc. I think steps should be reduced with the right regex match. The operator does not need surrounding spaces, but may have a space before and after, only before, or only after. Is there a way to handle all of these with one sed command?

There are many other conditions not mentioned also. The script takes more time to execute than desired.

The goal is to reduce the overall execution time so I am hoping to reduce the number of commands used with clever regex to match multiple conditions.

I'm also considering tr, awk or perl - whichever is fastest?


With GNU sed, you can use the | (or) operator:

$ sed -r 's/ *(\&\&|\|\|) */\1/g' <<< "foo && bar || baz"
  • *(\&\&|\|\|) *: search for zero or more space followed by any of the | separated strings followed by zero or more space
  • the matching strings are captured and output using backreference