anotheruser anotheruser - 1 year ago 96
Perl Question

match multiple conditions with GNU 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?

Answer Source

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


As pointed out in comments, you can use the -E flag with GNU sed in place of -r. Your command will be more portable:

sed -E 's/ *(\&\&|\|\|) */\1/g'

As GNU sed also supports \| alternation operator with Basic Regular Expressions, you can use it for better readability:

sed 's/ *\(&&\|||\) */\1/g'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download