Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print quotes between value using awk

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.

like image 520
Paul Avatar asked May 15 '26 01:05

Paul


2 Answers

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.

like image 133
Benjamin W. Avatar answered May 19 '26 04:05

Benjamin W.


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.

like image 28
Ed Morton Avatar answered May 19 '26 04:05

Ed Morton