Skip to main content

CSV - Add quotes around missing fields [Resolved]

My CSV file looks like this -

1,2,3,4,5,6,7,8
"AK","87","86","81","83","78",,

How do I transform it like this -

1,2,3,4,5,6,7,8
"AK","87","86","81","83","78","",""

Question Credit: eTEs
Question Reference
Asked September 21, 2019
Tags: linux
Posted Under: Unix Linux
21 views
2 Answers

I think a simple sed command will do:

sed -e 's/^,/"",/' -e 's/,$/,""/' -e 's/,,/,"",/g' file

Ouput (if there's a leading comma):

1,2,3,4,5,6,7,8
"","AK","87","86","81","83","78","",""

The first expression deals with a bare comma at the beginning of the line; the second expression deals with a bare comma at the end of the line; the third expression deals with misssing fields in the middle.


credit: NickD
Answered September 21, 2019

Sounds like you're doing csv processing manually. I don't know of any built-in csv reader in any language that wouldn't be able to process those empty fields without explicit quotes. You might want to rethink the way you process your csv file instead of trying to patch it.


credit: Michael Kelso
Answered September 21, 2019
Your Answer
D:\Adnan\Candoerz\CandoProject\vQA