Mayank Narang
Mayank Narang

Reputation: 13

How can I delete the last comma in each record of a comma-delimited csv?

Example Input : A,B,"C,D",E,F,G,

Example Output : A,B,"C,D",E,F,G

The issue I face with using the 'cut' command to accomplish the same is that my data has comma as well.

I wish to do the same in an automated process. So, Linux commands would be helpful.

Upvotes: 1

Views: 256

Answers (1)

Thomas
Thomas

Reputation: 181735

This should work:

sed 's/,$//g' < input_file.csv > output_file.csv

,$ is a regular expression that matches a comma at the end of each line. This gets replaced with the s command by nothing.

Proof:

$ echo 'A,B,"C,D",E,F,G,' | sed 's/,$//g'
A,B,"C,D",E,F,G

Note that some CSV dialects can also have line endings inside double quotes. If there happens to be a comma right before such a quoted line ending, that comma will also be stripped. If you want to handle this case correctly, you'll need a proper CSV parser.

Upvotes: 2

Related Questions