Combining Regular Expressions

We're using a script to parse files, and we would like to combine some regular expressions:

sed s/" "/""/g | sed s/,/\",\"/g | sed s/"^"/\"/g | sed s/"$"/\"/g

Is there a way to combine this into one regular expression?

Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

gabesoSolution ArchitectCommented:
This is to process a csv file.

You are eliminating spaces, then replacing commas with quote-comma-quote then finally wrapping the line with quotes: In order to turn a comma separated set of unquoted strings into a quoted set of strings.

I don't think you can do this in one regular expression because you are globally searching and replacing a sequence of patterns: This is at a higher level than the regular expression - more of a context free grammer type of thing - so you are into using perl perhaps and building a program around it.


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
You can combine multiple sed rules into a single command like this:

sed -e s/" "/""/g -e s/,/\",\"/g -e s/"^"/\"/g -e s/"$"/\"/g

..though I realise that's not exactly what you're asking, as it's still multiple regular expressions.

Ignoring the s/" "/""/ rule, if there is a known number of columns in your original file, then you can do something like:


With a regular expression, when you have \( <something> \), the actual text that matched the "something" can be inserted into the replacement string using \1, \2, \3.. for the first, second, third..., occurance of \(...\)

Although this doesn't answer your question exactly, it might help.  I also agree with gabeso, that it probably isn't possible to do this as a single regular expression.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.