Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Combining Regular Expressions

Posted on 2006-04-19
4
Medium Priority
?
252 Views
Last Modified: 2010-04-17
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?

Thanks!
0
Comment
Question by:dandrzejewski
2 Comments
 
LVL 9

Accepted Solution

by:
gabeso earned 500 total points
ID: 16491929
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.

0
 
LVL 3

Assisted Solution

by:steveiam
steveiam earned 500 total points
ID: 16494294
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:

s/^\(.*\),\(.*\),\(.*\)$/""\1","\2","\3","\4""/

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.
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Whether you’re a college noob or a soon-to-be pro, these tips are sure to help you in your journey to becoming a programming ninja and stand out from the crowd.
Q&A with Course Creator, Mark Lassoff, on the importance of HTML5 in the career of a modern-day developer.
Simple Linear Regression
Six Sigma Control Plans

810 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question