Skip to content

paste Command: Merging Lines from Files

Summary

The paste command in Linux is used to merge corresponding lines of multiple files. It reads each file line by line and combines the lines into a single line, separated by a delimiter (default is a tab). This is a powerful tool for creating structured data from separate files or combining data from different sources.

Introduction

The paste command provides a simple yet effective way to combine data horizontally from different files. It's particularly useful when you have data split across multiple files that you want to correlate or compare. Unlike commands like join which require matching fields, paste simply combines lines based on their position in the file. It can also be used with standard input.

Use case and Examples

Basic Usage: Merging Two Files

paste file1.txt file2.txt
This command merges file1.txt and file2.txt line by line, separating the content with a tab. The output is printed to standard output.

Using a Different Delimiter

paste -d "," file1.txt file2.txt
This command merges file1.txt and file2.txt using a comma (,) as the delimiter instead of the default tab.

Merging with Standard Input

ls -l | paste - file_sizes.txt
In this example, the output of ls -l is piped to paste. The - represents standard input. The output of ls -l is merged with the contents of file_sizes.txt, line by line.

Merging Multiple Files

paste file1.txt file2.txt file3.txt
This command merges the content of file1.txt, file2.txt, and file3.txt line by line.

Handling Unequal Length Files

paste file1.txt file2.txt
If file1.txt is shorter than file2.txt, the missing lines from file1.txt will be represented by empty fields (tabs in the output). The reverse is also true.

Commonly used flags

Flag Description Example
-d Specifies the delimiter to use instead of the default tab. paste -d ":" file1.txt file2.txt (uses : as the delimiter)
-s Merges all lines of each file into one line. paste -s file1.txt file2.txt (each file's content will become a single line)
- Represents standard input. cat file1.txt | paste - file2.txt (merges standard input with file2.txt)
-z Treats each file as zero-terminated lines, instead of newline-terminated. Useful for handling filenames containing newlines. find . -print0 | paste -z - <(printf '%s\0' "File Sizes:")


Share on Share on

Comments