Skip to content
Advertisement

Can ‘sed’ do ‘or’ class trimming?

I am working with a piece of code but it’s ugly. It has a nasty line in it along the lines of:

s/COM/ALPHA BETA GAMMA COM/g
s/DLX/ALPHA BETA GAMMA DLX/g
s/BE4/ALPHA BETA GAMMA BE4/g
s/BE2/ALPHA BETA GAMMA BE2/g
s/RS/ALPHA BETA GAMMA RS/g

If any of BE2, RS, etc. are found then it will replaced with Alpha Beta Gamma COM/DLX/BE4/BE2/RS. However, if all three are found then each one will be replaced. Since the ideal output would be:

ALPHA BETA GAMMA COM DLX BE4 BE2 RS

is there anyway to code this in sed please? It is truly “either NED or JED or TED.” Alternatively, can other Linux be used?

Advertisement

Answer

I understand you want to prepend a line having any of the alternatives you listed with ALPHA BETA GAMMA.

You may use

echo "COM, DLX, BE4, BE2 and RS" | sed -E 's/.*<(COM|DLX|BE4|BE2|RS)>/ALPHA BETA GAMMA &/'
# => ALPHA BETA GAMMA COM, DLX, BE4, BE2 and RS

See the online sed demo.

Details

  • -E – a POSIX ERE enabling option
  • .* – any 0+ chars
  • < – leading word boundary
  • (COM|DLX|BE4|BE2|RS) – matches COM or DLX or BE4 or BE2 or RS
  • > – trailing word boundary
  • ALPHA BETA GAMMA & – replace with ALPHA BETA GAMMA, space and the whole match value (&).
Advertisement