Search code examples
bashcsvquotation-marks

Bash - How to wrap values of the first line of a csv file with quotations


Line 1 of a csv file has the values separated by a comma like so:

word1,word2,word3,word4,word5

but needs to be wrapped with quotations like below:

"word1","word2","word3","word4","word5"

I would like a command to address line 1 only and leave the rest of the file alone.


Solution

  • Consider this test file:

    $ 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
    

    How it works

    • 1 { ... }

      This tells sed to perform the commands in braces only on line 1.

    • s/^/"/

      This puts a quote at the start of the line.

    • s/,/","/g

      This replaces each comma with quote-comma-quote.

    • s/$/"/

      This puts a quote at the end of the line.