Convert Multiple Rows into Single Row – Unix/Linux

  • Updated
  • Posted in Programming
  • 1 min read


Q) I’ve a merchandise knowledge within the textual content file. The knowledge within the file look as proven beneath:

> cat product.txt
iphone
samsung
nokia
yahoo
google
aol
amazon
ebay
walmart

Now my requirement is to group every 3 consecutive rows into a single row and produce a comma separated record of merchandise. The output ought to look as

iphone,samsung,nokia
yahoo,google,aol
amazon,ebay,walmart

I would like this to be applied utilizing unix or linux instructions in numerous methods?

Solution:

1. One means we are able to implement that is utilizing the awk command. The full awk command is proven beneath:

awk '{printf("%spercents",$0,NRpercent3?",":"n")}' merchandise.txt

2. Another means is utilizing the paste command. The resolution utilizing the paste command is proven beneath.

paste -d, - - - < merchandise.txt

Leave a Reply