I want to add quotes in all the fields of the CSV file.
My CSV file
$ cat file.csv
1,563,45645,example-text,/example/path,FILE,ftp://,11
Expected output
$ cat file.csv
"1","563","45645","example-text","/example/path","FILE","ftp://","11"
I want to add quotes in all the fields of the CSV file.
My CSV file
$ cat file.csv
1,563,45645,example-text,/example/path,FILE,ftp://,11
Expected output
$ cat file.csv
"1","563","45645","example-text","/example/path","FILE","ftp://","11"
try this:
sed "s/,/\",\"/g;s/\(.*\)/\"\1\"/" file.csv
explanation:
s/ # substitute
,/ # all ,
\",\" # with ","
/g # global on whole line
; # next expression
s/ # substitute
\(.*\)/ # save all into arg1 (\1)
\"\1\"/ # change to "\1"
There are many simple and direct ways to format your CSV file the way you want. However, if you want your CSV file to be RFC 1410 compliant you have to be a bit more careful. Especially with rule 7:
- If double-quotes are used to enclose fields, then a double-quote appearing inside a field must be escaped by preceding it with another double quote. For example:
"aaa","b""bb","ccc"
This gives the following awk solution:
awk 'BEGIN{FS=OFS=","}
{
for(i=1;i<=NF;++i) {
gsub("\042","\042\042",$i)
sub("^\042\042","",$i)
sub("\042\042$","",$i)
$i="\042" $i "\042"
}
}1' file.csv
If, in addition, you want to be compliant with rule 1:
- Each record is located on a separate line, delimited by a line break (
CRLF
). For example:
aaa,bbb,ccc CRLF
zzz,yyy,xxx CRLF
awk 'BEGIN{FS=OFS=","; ORS="\r\n"}
{
sub("\r$","")
for(i=1;i<=NF;++i) {
gsub("\042","\042\042",$i)
sub("^\042\042","",$i)
sub("\042\042$","",$i)
$i="\042" $i "\042"
}
}1' file.csv
Try Perl
$ cat smc.txt
1,563,45645,example-text,/example/path,FILE,ftp://,11
$ perl -lpe ' s/([^,]+)/"$1"/g ' smc.txt
"1","563","45645","example-text","/example/path","FILE","ftp://","11"
$
or using the lookarounds
$ perl -lne ' s/^|(?<=,)|(?=,)|$/"/g ; print ' smc.txt
"1","563","45645","example-text","/example/path","FILE","ftp://","11"
$