tags:

views:

30

answers:

2

I have a csv file that I need EVERY column wrapped in quotes. How do I change that using regex?

I am using my text editor to do the find/replace w/ regular expression (textmate)

example csv:

bear,brown,mean,large
ant,black,strong,tiny
cat,yellow,moody,small
A: 

You could start with:

find: ,
replace: "," 

then add a " at the start and at the end?

nicomen
If I'm not mistaken, I believe there is also a way to replace linebreaks in the same manner (thereby avoiding having to manually add the final quotes at start and end of each line). Although such characters may differ between text editors... In any case, just adding quotes the the start and end of document is not sufficient as that would transform the entire multi-row CSV document into a single-row CSV document.
gablin
You are correct, textmate regexps seems to support stuff like ^ and $, maybe that can be used to fix that: ^(.*)$ => "$1"
nicomen
A: 

Here are the important portions of the regex. Hopefully I got it right when I converted to textmate format:

Search - ([^,]*)(,|$)

Replace - "$1"$2

Search explanation: Find every character that is not a comma, up until we reach a comma, or the end of the line. Capture the match for string to be quoted in one variable, and capture the comma/end-of-line match in another variable.

Replace explanation: The original string, quoted, and the comma or end-of-line that follows it.

Merlyn Morgan-Graham