When you are wrangling raw data on a Linux server, you often encounter separated text files that need to be combined. If you have a file containing a list of employee first names (first.txt) and a completely separate file containing their last names (last.txt), using the standard cat command will simply stack the two lists vertically, putting all the last names at the very bottom. To merge the two files horizontally—stitching them together side-by-side into perfect columns—you must use the paste command.
How to Merge Files Horizontally
The paste command is a core GNU coreutil designed specifically for columnar text manipulation. It reads the first line of the first file, reads the first line of the second file, glues them together, and then moves down to the second line.
To merge our two name files, open the terminal and type:
paste first.txt last.txt
The output will immediately print to your screen. If line 1 of first.txt was “John” and line 1 of last.txt was “Smith”, the output will perfectly stitch them together as John Smith. The command automatically inserts a standard Tab character between the two merged words to ensure the columns align perfectly on your screen.
To save this newly merged data into a brand new, permanent file, use the standard bash redirection operator (>):
paste first.txt last.txt > full_names.txt
How to Change the Delimiter
While the default Tab character is excellent for visual formatting in the terminal, it is terrible if you intend to export the data into a spreadsheet application like Microsoft Excel or a database system. Those systems usually require a Comma-Separated Values (CSV) format.
You can instruct the paste command to swap the default Tab character for a strict comma by using the -d (delimiter) flag.
paste -d ',' first.txt last.txt > full_names.csv
The output is now formatted perfectly as John,Smith, ready to be instantly imported into any modern spreadsheet software.
How to Merge a File with Itself (Serialization)
The paste command has a highly specialized trick: it can take a single, massive vertical list and instantly reformat it into a compact horizontal paragraph using the -s (serial) flag.
If you have a file containing 50 IP addresses stacked vertically, and you need to feed all 50 of them into a firewall script on a single line separated by spaces, run:
paste -s -d ' ' ip_addresses.txt
The command instantly rips all the vertical line breaks out of the file, replacing them with spaces, transforming the massive vertical column into a single, perfectly formatted horizontal string.