Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash How to wrap values of the first line of a csv file with quotations, if they do not exist

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.

like image 427
Curious Sam Avatar asked Dec 02 '25 07:12

Curious Sam


1 Answers

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).

like image 92
Tom Fenech Avatar answered Dec 04 '25 22:12

Tom Fenech