1

I have a comma delimited file that looks like the following:

123,456,"ABC,DEF" 

I would like to change the file to a semi-colon delimited file:

123;456;"ABC,DEF" 

I have the following that I run but unfortunately the , in the quotes is also changed to ;. How can I stop this from happening?

sed 's/,/;/g; s/\"//g; s/$/;^/' input.csv > output.csv 

3 Answers 3

4

How can I change from comma-delimited to semi-colon delimited but don't change the commas that are in between quotes?

You can use csvtool. It is already packaged for many distributions. Handling the csv format with regular expressions can be both difficult and error prone.

$ csvtool -t ',' -u ';' col 1- input.csv > output.csv 
0

You can use awk with the double quote as fields separator and replace , with ; only for the odd fields (1,3,5 etc).

awk 'BEGIN{OFS=FS="\""} {for (i=1;i<=NF;i=i+2) gsub(/,/,";",$i)}1' file 

There are some assumptions made here, like that there are no ; into the fields initially, no embedded/escaped " inside double quotes, but the input is simple like in the example.

To deal with more complex cases, GNU awk provides an FPAT solution for csv files, which is efficient in most cases, excluding cases like newlines into the fields. If this cvs cannot be assumed as simple as in the example, then a program using a library for cvs parsing is required.

0

With GNU awk for FPAT:

$ awk -v FPAT='[^,]*|"[^"]+"' -v OFS=';' '{$1=$1}1' file 123;456;"ABC,DEF" 

If you need more than that then see https://stackoverflow.com/questions/45420535/whats-the-most-robust-way-to-efficiently-parse-csv-using-awk

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.