## 21.18. Pasting Things in Columns

Go to http://examples.oreilly.com/upt3 for more information on: cut+paste

Do you ever wish you could paste two (or even three) files side by side? You can, if you have the paste program (or the public-domain implementation on the disc).

For example, to create a three-column file from files x, y, and z:

>     $ paste x y z > file

To make paste read standard input, use the - option, and repeat `-` for every column you want. For example, to make an old ls (which lists files in a single column) list files in four columns:

>     $ ls | paste - - - -

The "standard input" option is also handy when used with cut (Section 21.14). You can cut data from one position on a line and paste it back on another.

The separate data streams being merged are separated by default with a tab, but you can change this with the -d option. Unlike the -d option to cut, you need not specify a single character; instead, you can specify a list of characters, which will be used in a circular fashion.

The characters in the list can be any regular character or the following escape sequences:

`\n`
  newline
`\t`
  tab
`\\`
  backslash
`\0`
  empty string

Use quoting (Section 27.12), if necessary, to protect characters from the shell.

There's also a -s option that lets you merge subsequent lines from one file. For example, to merge each pair of lines onto a single line:

>     $ paste -s -d"\t\n" list

Let's finish with one nice place to use process substitution, if your shell has it. You can use cut to grab certain columns from certain files, then use process substitution to make "files" that paste will read. Output those "files" into columns in any order you want. For example, to paste column 1 from file1 in the first output column, and column 3 from file2 in the second output column:

>     paste <(cut -f1 file1) <(cut -f3 file2)

If none of the shells on your system have process substitution, you can always use a bunch of temporary files, one file per column.

--TOR, DG, and JP

Copyright © 2003 O'Reilly & Associates. All rights reserved.