Convert column to quote and comma separated row

Hi,

I have a list of tables in a file.txt

C_CLAIM
 C_HLD
 C_PROVIDER

I want the output to be

'C_CLAIM','C_HLD','C_PROVIDER'

Currently I'm usin awk and getting output which is almost correct but still has minor defects

awk -vORS="','" '{ print $1 }' file.txt

The output of above command is

C_CLAIM','C_HLD','C_PROVIDER','

If you notice the first ' is missing and there is an extra ,' at the end.
Also a new line needs to be added at the end

I have other ways to complete this but all require multiple lines and creating temp files.
Any cleaner method will be appreciated.

Hello Wahi80,

Following may help you in same.

awk -vs1="'" '{S=S?S OFS s1 $0 s1:s1 $0 s1} END{print S}' OFS=,  Input_file

Output will be as follows.

'C_CLAIM','C_HLD','C_PROVIDER'

Thanks,
R. Singh

2 Likes

You can do without saving string

awk '{printf("%s'\''%s'\''",NR==1?"":OFS,$1)}END{print ""}' OFS=',' infile

---------- Post updated at 10:31 PM ---------- Previous update was at 10:25 PM ----------

Using Octal value

$ awk '{printf("%s\047%s\047",NR==1?"":OFS,$1)}END{print ""}' OFS=','  infile
'C_CLAIM','C_HLD','C_PROVIDER'

Using Hex value

$ awk '{printf("%s\x27%s\x27",NR==1?"":OFS,$1)}END{print ""}' OFS=','  infile
'C_CLAIM','C_HLD','C_PROVIDER'

Octal value I will recommend

Try:

awk '{printf fmt,$1}' fmt="'%s'\n" file | paste -sd, -

If you want to do it all in one invocation of awk and don't want to worry about the encoding of the single quote character, try:

awk -v q="'" '
NR!=1 {	printf("%s,", p) }
{	p = q $1 q }
END {	print p }' file.txt