Commands.page Logo

How to Concatenate Multiple Text Files in Ubuntu

Merging text files is a common task in Ubuntu Linux managed efficiently through the terminal. This article demonstrates the primary method using the cat command to join files into a new output file. You will also learn how to append content to an existing file without overwriting data.

Using the Cat Command

The most straightforward way to combine files is using the cat command followed by output redirection. Open your terminal and navigate to the directory containing your text files.

To merge file1.txt and file2.txt into a new file called combined.txt, run:

cat file1.txt file2.txt > combined.txt

The > operator creates combined.txt or overwrites it if it already exists. The files are joined in the order specified on the command line.

Appending to an Existing File

If you want to add content to a file that already contains data without deleting the existing content, use the >> operator instead of >.

cat file3.txt >> combined.txt

This command adds the content of file3.txt to the end of combined.txt.

Using Wildcards

You can concatenate all text files in a directory using a wildcard. Be aware that the order depends on alphabetical sorting.

cat *.txt > all_files.txt

This command combines every file ending in .txt within the current directory into all_files.txt.

Verifying the Output

After concatenating, you can verify the content using the cat command on the output file or check the line count with wc -l.

cat combined.txt
wc -l combined.txt

These steps ensure your files have been merged correctly without data loss.