Text-Fu · Lesson 7 of 16

paste

0 / 5 checkpoints answered

Full screen ↗

The paste command combines lines as columns. By default, it takes one line from each input file, joins those lines with a tab, and repeats until all inputs reach end-of-file.

Merging Files Side by Side

Create two small files:

$ printf 'alice\nbob\n' > names.txt
$ printf 'admin\nviewer\n' > roles.txt

Pass both files to paste:

$ paste names.txt roles.txt
alice	admin
bob	viewer

The visible spacing between columns is a tab. Unlike cat, which writes one complete file after another, paste combines corresponding input lines.

Checkfirst.txt contains A then B, and second.txt contains 1 then 2. What does paste first.txt second.txt produce by default?

Choosing a Delimiter

Use -d LIST to replace the default tab separator. For a colon:

$ paste -d ':' names.txt roles.txt
alice:admin
bob:viewer

Quote delimiters that have shell meaning. paste can cycle through multiple delimiter characters when the list contains more than one, but a single character is easiest when building two columns.

CheckWhich command joins corresponding lines from names.txt and roles.txt with a colon?

Serializing Lines from One File

The -s option processes each input file serially, joining its lines into one output line. Create a file with one word per line:

$ printf 'The\nquick\nbrown\nfox\n' > words.txt
$ paste -s words.txt
The	quick	brown	fox

Combine -s with -d to choose the separator:

$ paste -s -d ' ' words.txt
The quick brown fox

If several files are supplied with -s, each file becomes its own output line.

CheckWhich command joins every line of words.txt into one space-separated output line?

Handling Unequal Input Lengths

When parallel input files have different numbers of lines, paste continues until the longest file ends. Missing values from a shorter file become empty fields:

$ printf 'A\nB\nC\n' > letters.txt
$ printf '1\n2\n' > numbers.txt
$ paste -d ':' letters.txt numbers.txt
A:1
B:2
C:

CheckWhat happens when one file passed to parallel paste ends before another?

Reading One Input from stdin

Use - as a file operand to read that position from stdin:

$ printf 'admin\nviewer\n' | paste -d ':' names.txt -
alice:admin
bob:viewer

CheckIn producer | paste names.txt -, what does the - operand mean?

To practice merging line-oriented data, try this hands-on lab:

  1. Simple Text Processing - Learn to use powerful commands like tr, col, join, and paste to manipulate and analyze text data efficiently.

Summary

You can now combine line-oriented inputs with predictable alignment and delimiters.

  1. Merge corresponding lines from several files.
  2. Replace the default tab separator with -d.
  3. Serialize one file's lines with -s.
  4. Interpret empty fields from shorter inputs.
  5. Use - when one input comes from stdin.