Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change last record separator with awk

Tags:

bash

awk

I have an input file as below:

apple 6
banana 7
goat 8

and I need output as

{6,apple},
{7,banana},
{8,goat}

However, when I run the awk as below, it is printing extra last comma (,). How to avoid that last comma ?

awk '{print "{"$2","$1"},"}' data
{6,apple},
{7,banana},
{8,goat},

Update:

Actually, I needed output like this

{6,apple},
{7,banana},
{8,goat}
] 

and when I run

awk '{print "{"$2","$1"},"}' END {print "\t\t]\n}' data

it gives me

{6,apple},
{7,banana},
{8,goat}, 
] 

I don't need the last comma... How to it avoid in this case?

like image 266
Media Avatar asked Oct 20 '25 14:10

Media


2 Answers

Using printf and delayed printf of the comma:

$ awk '{printf "%s{%s,%s}",(NR==1?"":"," ORS),$2,$1} END{print ORS "]"}' file
{6,apple},
{7,banana},
{8,goat}
]
like image 116
James Brown Avatar answered Oct 23 '25 05:10

James Brown


How about piping it to sed with the following command line ?

awk ... | sed '$ s/,$//' 
like image 25
DaLynX Avatar answered Oct 23 '25 05:10

DaLynX