0

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?

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

4 Comments

Perfect.. if you dont mind, can you please explain AS[^,]+ part in sed? and how it replaces even instances without a comma
@OptimusPrime Sure. Note that here AS[^,]* would do, no need for + (which is a Exteneded regex pattern, matches one or more of the preceding token). So in AS[^,]*, AS matches AS literally, [^,] matches any character except ,, the following * matches zero or more of such characters, so it eventually matches everything till next ,.
Makes Sense!!! One more question, can we do adjustments within that sed to make AS case insensitive? i.e. match if it is AS or as?
@OptimusPrime Do sed 's/[[:blank:]][AaSs][^,]*//g'
1

You can use a negated character class as

sed 's/AS[^,]*//g'
  • [^,]* Matches zero or more non , characters. Which means that it matches till the immediate , and replace it with null

Example

>>> echo "EONV.BUY AS BUY, CONV.CUSTOM1 AS CUSTOM1 , TP.BUY AS BUY, TP.CUSTOM1 AS CUSTOM1" | gsed 's/AS[^,]*//g'
EONV.BUY , CONV.CUSTOM1 , TP.BUY , TP.CUSTOM1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.