Stefan
Stefan

Reputation: 1533

Bash rows to column

I know how to transpose rows in a file to columns, but I want to append the lines of the bottom half of a file to the lines to the upper half.

Like:

A1
A2
A3
B1
B2
B3

to

A1 | B1
A2 | B2
A3 | B3

the list comes from two greps. I append the first grep with the second one. The two greps have the same amount of hits.

I want to do this within a bash script.

Upvotes: 0

Views: 138

Answers (4)

Ed Morton
Ed Morton

Reputation: 203169

$ awk '{a[NR]=$0} END{ m=NR/2; for (i=1;i<=m;i++) print a[i] " | " a[i+m]}' file
A1 | B1
A2 | B2
A3 | B3

Upvotes: 2

glenn jackman
glenn jackman

Reputation: 246744

You're looking for the pr tool:

printf "%s\n" {A,B}{1,2,3}   |   pr -2 -T -s" | "
A1 | B1
A2 | B2
A3 | B3

Upvotes: 2

fejese
fejese

Reputation: 4628

Just as an alternative:

awk 'BEGIN{c=0}
     {a[c++] = $1}
     END { for (i = 0; i < c/2; i++) print a[i] " " a[i+c/2]}'

This assumes you have an even number of lines as input.

Upvotes: 1

fedorqui
fedorqui

Reputation: 289495

What about combining head and tail together with paste?

paste -d'|' <(head -3 file) <(tail -3 file)

It returns:

A1|B1
A2|B2
A3|B3

paste merges lines of files. If we provide different lines from the same file... that's all!

As it is a matter of getting head from the half of the lines and tail from the rest, this is a more generic way:

paste -d'|' <(head -n $(($(wc -l <file)/2)) file) 
            <(tail -n $(($(wc -l <file)/2)) file)

Upvotes: 2

Related Questions