regex - Wrap a single field with single quotes using awk -
there number of examples using awk wrap fields double quotes. have unsuccessfully been trying enclose field single quotes data loading csv files in postgresql.
below few of attempts:
#!/usr/bin/awk -f begin { fs=ofs=","} { (i = 1; <= nf; ++i) if($i == 9) { $i = "\'' $i \''" } print $0 >> "output.csv" }
or
awk 'begin { ofs=fs="," } { $9= ""'" $9 ""'"} 1' container.csv > output.csv
also...
awk -v q="'" 'begin { fs="," } { sub($9, ""\'"&"\'"" );print}' container.csv > output.csv
$ awk 'begin { fs = ofs = "," } { $9= "'"'"'" $9 "'"'"'"; print }' \ > <<<one,two,three,four,five,six,seven,eight,nine,ten one,two,three,four,five,six,seven,eight,'nine',ten
the tricky thing here getting quotes through bash awk -- if have single quote in single-quoted command-line argument, it's treating ending quoting context started @ 'begin
, not literal thing sent awk
.
thus, "'"'"'"
necessary trickery:
- the first character,
"
, literal, passed awk - the second character,
'
, syntactic, used tell shell end quotes began @ front of command line - the third character,
"
, syntactic, used begin new (double-quoted) quoting context. - the fourth character,
'
, literal inside context. - the fifth character,
"
, ends double-quoting context started @ character three - the sixth character,
'
, syntactic, resuming single-quoted context ended character two - the seventh character,
"
, literal, passed awk.
thus, what's actually passed awk
used script in above is:
begin { fs = ofs = "," } { $9= "'" $9 "'"; print }
...which put directly in file, if preferred; if awk script had #!/usr/bin/awk -f
shebang, should work when directly executed command.
if shell bash, way, there's alternate quoting context make less awful:
$ awk $'begin { fs = ofs = "," } { $9= "\'" $9 "\'"; print }'
inside of $''
, backslash escapes honored -- \t
tab, \f
field separator, \r
newline, , -- relevant our point -- \'
single quote.
Comments
Post a Comment