When working with raw data in the Linux terminal, you frequently encounter situations where related information is stored in completely separate text files. For example, you might have one file containing a list of employee names (names.txt) and a second file containing a list of their corresponding email addresses (emails.txt). If you need to combine this data to create a master CSV file for import into a database, manually copying and pasting the lines is impossible at scale. While commands like cat append files vertically (placing the emails beneath the names), the Linux paste command is specifically designed to merge files horizontally, joining them side-by-side on a line-by-line basis.
Basic Side-by-Side Merging
The paste command reads multiple files sequentially and outputs the corresponding lines merged together, separated by a standard Tab character.
- Open your terminal application.
- Ensure you have two text files with an identical number of lines. (If file A has 10 lines and file B has 15, the final 5 lines of file B will be merged with blank space).
- Type the command followed by the file names:
paste names.txt emails.txt - Press Enter.
The output will immediately print to your screen. Line 1 of names.txt will appear, followed by a Tab space, followed by Line 1 of emails.txt, creating a neat two-column list.
Changing the Delimiter
While a Tab space is useful for visual reading in the terminal, it is often the wrong format if you are preparing data for another program. If you are building a Comma-Separated Values (CSV) file, you must force the paste command to use a comma to separate the merged lines instead of a Tab. This is achieved using the -d (delimiter) flag.
paste -d ',' names.txt emails.txt
The output will now look like this: John Doe,[email protected].
You can use almost any character as a delimiter. If you are generating a list of system paths, you might use a forward slash (-d '/'). If you want no separation at all, jamming the two strings directly together, you can specify an empty delimiter using null bytes (-d '\0').
Saving the Merged Output
By default, paste simply prints the merged text to standard output (your screen) and immediately forgets it. To permanently save the joined data into a new file, you must use standard bash redirection (>).
- Run the paste command with your chosen delimiter, and redirect the output to a new filename:
paste -d ',' names.txt emails.txt > master_directory.csv - Press Enter.
The terminal will not output any text, but if you run cat master_directory.csv, you will see your perfectly merged, side-by-side data safely stored in the new file.