When working with text files in Linux, you often need to manipulate columns of data. You might have one text file containing a list of usernames, and a completely separate text file containing a list of IP addresses. If you need to combine them side-by-side into a single report, standard commands like cat will not work; cat stacks files vertically, placing the IPs at the very bottom of the usernames.
To stitch files together horizontally, you must use the paste command. paste reads multiple files simultaneously and merges them line by line, creating perfect side-by-side columns.
In this guide, you will learn how to use the paste command to merge files and control how the data is separated.
The Basic paste Command
The syntax for paste is simple. You call the command followed by the names of the files you wish to merge.
paste file1.txt file2.txt
Imagine names.txt contains three lines (Alice, Bob, Charlie) and ips.txt contains three lines (10.0.0.1, 10.0.0.2, 10.0.0.3).
If you run paste names.txt ips.txt, the terminal will output:
Alice 10.0.0.1
Bob 10.0.0.2
Charlie 10.0.0.3
By default, the paste command places a Tab character between the two columns to keep them visually aligned.
Changing the Delimiter (The -d Flag)
While a Tab character is great for visual reading in the terminal, it is often terrible for scripting or exporting data to a spreadsheet. You usually want the columns separated by a comma to create a CSV (Comma Separated Values) format.
You can change the separator using the -d (delimiter) flag, followed by the character you want to use inside quotation marks.
paste -d "," names.txt ips.txt
The output instantly changes to a strict CSV format:
Alice,10.0.0.1
Bob,10.0.0.2
Charlie,10.0.0.3
You can use almost any character as a delimiter: a hyphen -d "-", a colon -d ":", or even a space -d " ".
Merging a File into a Single Line (The -s Flag)
The paste command has a secondary, highly useful function known as “serial” merging. Instead of merging two files side-by-side, it can take a single vertical file and crush it horizontally into one long string.
You achieve this using the -s (serial) flag. If you run it on names.txt:
paste -s names.txt
The output will be: Alice Bob Charlie
This is incredibly powerful when combined with the delimiter flag. If you have a file with 100 IP addresses, one per line, and you need to feed them into a firewall script as a single comma-separated list, you do not need to write a complex loop. You simply run:
paste -s -d "," ips.txt
This single command transforms the 100-line vertical file into one horizontal string: 10.0.0.1,10.0.0.2,10.0.0.3...
By utilizing the paste command, you can rapidly reshape text data for reports, CSV exports, or input for other command-line tools without writing complex processing scripts.