If you are working with structured data across multiple files in a Linux terminal, such as a list of first names in one file and a list of last names in another, combining them manually is incredibly tedious. While the cat command is great for appending one file to the absolute bottom of another (serial concatenation), it cannot merge files side-by-side. To combine files in parallel, merging their corresponding lines horizontally, you must use the paste command.
How the paste Command Works
The paste utility reads lines from multiple files sequentially and merges them together, separated by a standard Tab character, printing the final result to the standard output.
For example, imagine you have two files. names.txt contains three names (Alice, Bob, Charlie) and jobs.txt contains three occupations (Engineer, Teacher, Doctor). To merge these lists perfectly, simply type:
paste names.txt jobs.txt
The output will be perfectly aligned:
Alice Engineer
Bob Teacher
Charlie Doctor
If you want to save this new, combined list to a permanent file, you simply redirect the output using the > operator.
paste names.txt jobs.txt > combined_staff.txt
How to Change the Delimiter
By default, paste uses a Tab character to separate the merged data. If you are preparing this data to be imported into a spreadsheet program like Microsoft Excel, you likely want to format it as a Comma-Separated Values (CSV) file instead. You can change the delimiter using the -d flag.
paste -d ',' names.txt jobs.txt
The output will now be comma-separated: Alice,Engineer. You can use almost any character as a delimiter, including colons, dashes, or pipes.
How to Merge Lines Serially
In a unique twist, the paste command can also be used on a single file to convert a vertical list into a horizontal string. This is done using the -s (serial) flag.
If you have a file containing a long vertical list of IP addresses, and you need them formatted as a single comma-separated string to paste into a firewall configuration script, you can use:
paste -s -d ',' ip_addresses.txt
Instead of merging multiple files, this command takes all the lines inside ip_addresses.txt and pastes them together end-to-end, producing a clean, single-line output.