paste Command in Linux with Examples

The paste command is used to combine multiple files into a single output. Recall the fictional piece of paper which listed rows of names, email addresses, and phone numbers. After tearing the paper into three columns, what if we had glued the first back to the third, leaving a piece of paper listing only names and phone numbers? This is the concept behind the paste command.

The paste command expects a series of filenames as arguments. The paste command will read the first line from each file, join the contents of each line inserting a TAB character in between, and write the resulting single line to standard out. It then continues with the second line from each file.

Consider the following two files as an example.

$ cat file-1
File-1 Line 1
File-1 Line 2
File-1 Line 3
$ cat file-2
File-2 Line 1
File-2 Line 2
File-2 Line 3

The paste command would output this:

$ paste file-1 file-2
File-1 Line 1 File-2 Line 1
File-1 Line 2 File-2 Line 2
File-1 Line 3 File-2 Line 3

If we had more than two files, the first line of each file would become the first line of the output. The second output line would contain the second lines of each input file, obtained in the order we gave them on the command line. As a convenience, the filename - can be supplied on the command line. For this “file”, the paste command would read from standard in.

Command Line Switches for paste

Option Description
-d list Reuse characters from list for delimiters (instead of the default TAB character).
-s, –serial Transpose the result, so that each line in the first file is pasted into a single line, each line of the second file is pasted into the next single line, etc.

Examples of Pasting

Our initial example showed the most common usage of paste, where the first lines from all the input files are concatenated together and separated by a delimiter character; the process then repeats for the subsequent lines. The -s option pastes all the lines from the first input file into the first output line, then pastes all the lines from the second input file into the second output line, and so on:

$ paste -d: -s file-1 file-2
File-1 Line 1:File-1 Line 2:File-1 Line 3
File-2 Line 1:File-2 Line 2:File-2 Line 3

Recall that the -d switch list argument can take more than one character. This can be used to provide a different delimiter between each pair of portions written to the output. The list characters are recycled if necessary:

$ paste -d+-/ file-1 file-2 file-1 file-2 file-1
File-1 Line 1+File-2 Line 1-File-1 Line 1/File-2 Line 1+File-1 Line 1
File-1 Line 2+File-2 Line 2-File-1 Line 2/File-2 Line 2+File-1 Line 2
File-1 Line 3+File-2 Line 3-File-1 Line 3/File-2 Line 3+File-1 Line 3