Reputation: 321
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.
Upvotes: 2
Views: 4734
Reputation: 67507
another awk
$ awk -F'|' -v OFS='","' -v q='"' '{$0=q $0 q; $1=$1}1' file
"A","B","C","D","E","F"
field separators are handled by awk
automatically, just needs help for the first and last fields. Equivalently,
$ awk -F'|' -v OFS='","' -v q='"' '{$1=q $1; $NF=$NF q}1' file
"A","B","C","D","E","F"
Upvotes: 4
Reputation: 203532
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.
Upvotes: 5
Reputation: 52142
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.
Upvotes: 5