Paste Command - Concatenate and Format Files | Online Free DevTools by Hexmos

Learn to use the paste command for concatenating files and formatting text. Explore examples for combining columns, listing files, and numbering lines with this essential Linux utility.

Paste Command Examples

The paste command in Linux is a powerful utility used to merge lines of files. It can concatenate lines from multiple files, either column by column or line by line, making it invaluable for text processing and data manipulation in the command line. This tool is essential for developers and system administrators working with shell scripts.

Concatenate Columns from Files

The most common use of the paste command is to combine corresponding lines from multiple files into a single line, separated by a tab character by default. This is useful for joining related data from different sources.

# To concat columns from files:
paste <file1> <file2> ...

List Files in Columns

You can use paste in conjunction with other commands like ls to format output. For instance, to display a list of files in the current directory across three columns, you can pipe the output of ls to paste.

# To list the files in the current directory in three columns:
ls | paste - - -

Combine Lines Sequentially

The -s option allows you to paste lines sequentially from a single file, rather than in parallel. This is useful for transforming multi-line records into single-line entries, often with a specified delimiter.

# To combine pairs of lines from a file into single lines:
paste -s -d '\t\n' <file>

Number Lines in a File

While nl is the dedicated command for numbering lines, paste can achieve a similar result by combining the output of sed (which prefixes lines with numbers) with itself.

# To number the lines in a file, similar to nl(1):
sed = <file> | paste -s -d '\t\n' - -

Create PATH-like Strings

paste can be used to format directory paths into a colon-separated string, which is commonly used for environment variables like PATH. This example finds all directories named 'bin' and formats their paths.

# To create a colon-separated list of directories named bin, suitable for use in the PATH environment variable:
find / -name bin -type d | paste -s -d : -

Further Reading: