1

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.

Cyrus
  • 84,225
  • 14
  • 89
  • 153
Vituvo
  • 1,008
  • 1
  • 9
  • 29

2 Answers2

2

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.

John1024
  • 109,961
  • 14
  • 137
  • 171
0

awk alternative approach:

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