0

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.

1
  • Try to give more context on your greps, etc, so that we can provide better answers. Also, what did you try so far? Commented Oct 8, 2014 at 15:48

4 Answers 4

2

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)
Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

On Solaris: pr -2 -T -s" | " -> pr: illegal option -- T and pr -2 -s" | " -> pr: illegal option -- |. Is this GNU pr or something?
2
$ 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

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.