The other day I asked how to wrap values of the first line of a csv file with quotations. I was given this reply which worked great.
$ cat file.csv
word1,word2,word3,word4,word5
12345,12346,12347,12348,12349
To put quotes around the items in the first line only:
$ sed '1 { s/^/"/; s/,/","/g; s/$/"/ }' file.csv
"word1","word2","word3","word4","word5"
12345,12346,12347,12348,12349
I now need to test if the quotes exist around the values to eliminate chances of double quoting values.
Change each of the substitutions to include optional quotes:
sed -E '1 { s/^"?/"/; s/"?,"?/","/g; s/"?$/"/ }' file.csv
I have added -E to enable extended mode, so that ? is understood to mean "0 or 1 match".
You could also keep on using basic mode (no -E) and replace each ? with either \{0,1\} (again, 0 or 1 match) or * (which matches 0 or more).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With