user1907831
user1907831

Reputation: 11

How to convert columns to rows in unix?

my input file is:

zoo1
----

cat
dog
mouse

zoo2
----

lion
tiger
zebra

I want my output file to be:

cat,dog,mouse
lion,tiger,zebra

Any idea how?

Upvotes: 1

Views: 9036

Answers (4)

leggewie
leggewie

Reputation: 272

tr provides a very simple and easy to understand way to do this.

tr -s \\n ","

http://linuxcommand.org/lc3_man_pages/tr1.html

Upvotes: 1

terdon
terdon

Reputation: 3380

You can do this by using perl's paragraph mode:

$ perl -000 -ne 'next if /---/;print join(",",split(/\n/)),"\n"' file
cat,dog,mouse
lion,tiger,zebra

From man perlrun:

-0[octal/hexadecimal]
     specifies the input record separator ($/) as an octal or hexadecimal number.
     If there are no digits, the null character is the separator.  Other switches
     may precede or follow the digits.  For example, if you have a version of 
     find which can print filenames terminated by the null character, you can say
     this:

            find . -name '*.orig' -print0 | perl -n0e unlink

     The special value 00 will cause Perl to slurp files in paragraph mode.  
     Any value 0400 or above will cause Perl to slurp files whole, but by 
     convention the value 0777 is the one normally used for this purpose.

Upvotes: 0

Chris Seymour
Chris Seymour

Reputation: 85913

One way with awk:

$ awk '!(NR%2){$1=$1;print}' FS='\n' OFS=',' RS= file
cat,dog,mouse
lion,tiger,zebra

Upvotes: 2

Kent
Kent

Reputation: 195289

for the example in your question, this one-liner works:

 awk -v RS= '/----/{next}{gsub(/\n/,",")}7' file

or by setting the OFS and FS:

awk -v RS= -v OFS="," -F'\n' '/----/{next}$1=$1' file

little test:

kent$  awk -v RS= '/----/{next}{gsub(/\n/,",")}7' f
cat,dog,mouse
lion,tiger,zebra



kent$  awk -v RS= -v OFS="," -F'\n' '/----/{next}$1=$1' f
cat,dog,mouse
lion,tiger,zebra

Upvotes: 2

Related Questions