6

I have a textfile like:

Adam
Bob
Cevin
David
Evan

If I "paste - -" it, I get:

Adam   Bob
Cevin  David
Evan

But I need that the lower half will be added as a new column:

Adam  David
Bob   Evan
Cevin

Is there a easy way to do this?

3
  • So you want to split the input file in two columns while retaining its order? Commented Nov 30, 2016 at 10:06
  • Yeah right, pr -t2 worked :) Commented Nov 30, 2016 at 10:09
  • 4
    Looks like you want to print the columns down rather than across, and it doesn't have much to do with sorting. Commented Nov 30, 2016 at 10:19

1 Answer 1

9

You could use:

pr -t -2 file

Beware it truncates the lines that are wider than half the page width (72 characters by default, see the -w option to change it).

(note that with the GNU implementation, the column alignment may be off if the file contains multi-byte or zero-width or double-width characters). Or:

pr -t -2 -s file

to separate the columns with one tab character like paste does (there's no truncation then).

Note however that pr treats the form-feed character (^L) as a page delimiter. Not a problem if that character is not present in your file.

Or with zsh:

print -r -C2 -- ${(f)"$(<file)"}
  • $(<file): grab the content of file
  • (f): split it on linefeed (newline) characters
  • -r: print raw
  • -C2: on 2 Columns.
4
  • I've tried reading the man page for pr and couldn't find where it accepts a number after -t... would you tell me? I always find man pages difficult. thanks! Commented Nov 30, 2016 at 12:50
  • 2
    @JorgeeFG That's not a number after -t, that's the -2 option. -COLUMN, --columns=COLUMN in the GNU pr man page. I'll break the -t2 down in the answer to avoid confusion. Commented Nov 30, 2016 at 13:00
  • So do you mean for the other types of characters, you suggest we use pr, but a non-GNU implementation? Commented Nov 30, 2016 at 18:17
  • 1
    @Pysis, if you care about column alignment with non-ASCII text, then yes. You could try the pr from the heirloom toolchest which seems to work OK. Commented Nov 30, 2016 at 19:05

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.