peon
peon

Reputation: 13

Mulitiple rows to single line

Input Name Rico

Address Australia

Age 24

Name Rica

Address Asia

Age 25

Output Name Rico, Address Australia, Age 24

Name Rica, Address Asia, Age 25

Can we do this in Unix?

Upvotes: 0

Views: 67

Answers (4)

peon
peon

Reputation: 13

I found the solution:

awk 'BEGIN { RS="" ; FS="\n"}; { print $1,$2 }' file

This sets the input record separator as a blank line, or consecutive blank lines for this matter, as the next record will be next non-blank line. This also sets the field separator as nextline.

Upvotes: 0

tso
tso

Reputation: 4924

with sed:

sed ':a;N;$!ba;s/\n/, /g' filename

Upvotes: 1

hiropon
hiropon

Reputation: 1802

You can do converting multiple lines to single line with using awk.

#!/usr/bin/awk
# table.awk

{
    if (NR == 1) {
        printf("%s",$0);
    } else {
        printf(",%s",$0);
    }
}

$ cat input.csv

Name Rico
Address Australia
Age 24
Name Rica
Address Asia
Age 25

$ awk -f table.awk input.csv

Name Rico,Address Australia,Age 24,Name Rica,Address Asia,Age 25

There are more efficient answers in Stackoverflow, like following:

How to merge rows from the same column using unix tools

Upvotes: 0

karakfa
karakfa

Reputation: 67467

here is another alternative...

paste -sd, inputfile

Upvotes: 0

Related Questions