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

136 views Asked by At

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.

2

There are 2 answers

1
John1024 On BEST ANSWER

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.

1
RomanPerekhrest On

awk alternative approach:

awk -F, 'NR==1{ gsub(/[^,]+/,"\"&\"",$0) }1' file
  • NR==1 - consider only the 1st record