bashcsvif-statementquotations

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.


Solution

  • This problem suits awk more than sed due to row/column processing:

    awk 'BEGIN{FS=OFS=","} NR==1 {
       for (i=1; i<=NF; i++) {gsub(/^"|"$/, "", $i); $i = "\"" $i "\""}
    } 1' file
    
    "word1","word2","word3","word4","word5"
    12345,12346,12347,12348,12349