Skip to content

Linux Foundations / Find your way around Linux ยท Step 37 of 63

Lesson: pasteSwitch
โ† Linux Foundations

Shell and files

paste

Learn to merge lines from files side by side or join them into one line with paste.

paste joins lines together. Where cat puts files one after another, paste puts them next to each other.

Files side by side

$ cat names.txt
maya
omar
$ cat cities.txt
London
Cairo
$ paste names.txt cities.txt
maya	London
omar	Cairo

Line 1 of each file forms output line 1, and so on. The columns are separated by a tab. paste does not compare the contents, so the files must already be in matching order.

If one file is shorter, paste carries on and leaves its column empty for the remaining lines.

Choose the delimiter

-d replaces the tab.

$ paste -d ',' names.txt cities.txt
maya,London
omar,Cairo

If you give several characters, such as -d ':;', they are used in turn between the columns.

Serial mode

-s turns the work sideways: it joins all the lines of one file into a single line.

$ paste -s names.txt
maya	omar
$ paste -s -d ',' names.txt
maya,omar

With several files, -s produces one output line per file.

Read from stdin

A - in place of a file name means standard input. Each - takes the next line in turn, which is a neat way to fold a list into columns.

$ printf 'a\nb\nc\nd\n' | paste - -
a	b
c	d

You can mix - with real files:

$ ls | head -n 2 | paste - cities.txt

paste or join?

paste matches lines only by position. If you need to match records by a shared value, such as a user ID, use join, covered later. If your files came from Windows, stray carriage returns can make paste output look scrambled.

Try these in the streams and text lab.

Try it

  1. Make two three-line files with printf '1\n2\n3\n' > n.txt and printf 'x\ny\nz\n' > l.txt.
  2. Run paste n.txt l.txt.
  3. Run paste -d '=' l.txt n.txt.
  4. Run paste -s -d '+' n.txt.

Check your understanding

paste

All 5 sections ยท no timer

Unlimited retries

Questions from every section are combined into one assessment. Answer them all correctly to complete the article.

Your completion saves in this browser. Sign in to sync it to your account.