Optimus Prime Optimus Prime - 2 months ago 8
Bash Question

String pattern replace using sed in Shell

I would like to remove the "AS" part in the below string,

CONV.BUY AS BUY, CONV.CUSTOM1 AS CUSTOM1 , TP.BUY AS BUY, TP.CUSTOM1 AS CUSTOM1


should be changed to

CONV.BUY, CONV.CUSTOM1, TP.BUY, TP.CUSTOM1


What i did is

echo $string | sed -e 's/ AS.*\,/\,/g'


which gives

CONV.BUY, TP.CUSTOM1 AS CUSTOM1


Two fields are filtered off in that sed. Is there any better solution to achieve my objective without using a loop?

Answer

With sed:

sed 's/[[:blank:]]AS[^,]*//g'
  • [[:blank:]]AS matches AS preceded by a whitespace, then [^,]* matches upto the next ,. All such matched portions are removed by replacing with null.

Example:

% sed 's/[[:blank:]]AS[^,]*//g' <<<'CONV.BUY AS BUY, CONV.CUSTOM1 AS CUSTOM1 , TP.BUY AS BUY, TP.CUSTOM1 AS CUSTOM1'
CONV.BUY, CONV.CUSTOM1, TP.BUY, TP.CUSTOM1