3

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?

andrey
  • 588
  • 1
  • 8
  • 14
Media
  • 47
  • 2
  • Possible duplicate of [How can I remove the last character of a file in unix?](https://stackoverflow.com/questions/27305177/how-can-i-remove-the-last-character-of-a-file-in-unix) – l'L'l Dec 23 '18 at 02:17

6 Answers6

2

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

awk ... | sed '$ s/,$//' 
DaLynX
  • 328
  • 1
  • 11
2

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}
]
James Brown
  • 36,089
  • 7
  • 43
  • 59
1

here is one alternative

$ awk 'NR==FNR{n=NR; next} {print "{" $2 "," $1 "}" (FNR==n?"\n]":",")}' file{,}

{6,apple},
{7,banana},
{8,goat}
]
karakfa
  • 66,216
  • 7
  • 41
  • 56
1

Just delay the output:

awk 'NR>1{print lastline} {lastline="{" $2 "," $1 "},"; } END{print substr(lastline, 1, length(lastline)-1)}' data

each line print last line's output, at the end strip last comma and print it.

Til
  • 5,150
  • 13
  • 26
  • 34
1
awk 'BEGIN{ORS=",\n"} {if (NR>1) {print prev} prev="{"$2","$1"}"} END{ORS=""; print prev}'
andrey
  • 588
  • 1
  • 8
  • 14
0

Here is the Perl solution

/tmp> cat media.txt
apple 6
banana 7
goat 8
/tmp> perl -lne ' s/(\S+) (\d+)/{$2,$1}/g; if(eof) { print "$_\n]" } else { print "$_," } ' media.txt
{6,apple},
{7,banana},
{8,goat}
]
/tmp>

Or

$ perl -lne ' s/(\S+) (\d+)/{$2,$1}/g; print eof ? "$_\n]" : "$_," ' media.txt
{6,apple},
{7,banana},
{8,goat}
]

If your file can fit into memory, the below Perl solution would work

/tmp> perl -0777 -ne ' s/(\S+) (\d+)/{$2,$1}/g ; print join(",\n",split)."\n]\n" ' media.txt
{6,apple},
{7,banana},
{8,goat}
]
/tmp>
stack0114106
  • 8,534
  • 3
  • 13
  • 38