I have a file
A|B|C|D|E|F
I need output like
"A","B","C","D","E","F"
I did:
awk -f'|' '{print $1,$2,$3}'
This gives me output just with spaces. My question is how to get comma separated output with quotes, and how to print all values at once without typing '{print $1,$2,$3......}'
I can do:
awk -f'|' '{print """"$1""""","""""$2""""","""""$3""""..}'
But it does not work.
To specify the field separator, you have to use -F instead of -f; to change what the field separator is for the output, you have to change the OFS variable (the output field separator).
The get quotes around your fields, you can loop over all fields and add them:
$ awk -F"|" -v OFS="," '{for (i=1; i<=NF; ++i){$i="\""$i"\""}}1' infile
"A","B","C","D","E","F"
Alternatively, using sed:
$ sed 's/\([^|]*\)/"\1"/g;y/|/,/' infile
"A","B","C","D","E","F"
This surrounds all sequences of non-pipe characters with quotes, then substitutes all the pipes with commas.
The idiomatic awk solution is to tell awk what the input field separator (FS) is and what you want the output field separator (OFS) to be and then simply update a field so awk converts all FSs to OFSs.
So that could be this:
$ awk -F'|' -v OFS='","' '{$1=$1; print "\"" $0 "\""}' file
"A","B","C","D","E","F"
or this:
$ awk -F'|' -v OFS='","' '{$1=$1; gsub(/^|$/,"\"")} 1' file
"A","B","C","D","E","F"
or @karakfa's alternative https://stackoverflow.com/a/35607361/1745001 or various other similar solutions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With