Bash: How to Concatenate Multiple Files into One File


Often you may want to use Bash to concatenate multiple text files into a single file.

You can use the following syntax to do so:

cat *.txt > all_data.txt

This particular example concatenates all files that have a .txt extension in the current directory into a single file named all_data.txt.

It’s important to note that Bash will concatenate the files based on alphabetical name of the files by default.

However, you can type the names of the individual files in a specific order to instead concatenate them in that particular order:

cat data2.txt data3.txt data1.txt > all_data.txt

The following example shows how to concatenate multiple text files into a single file in practice.

Example: How to Concatenate Multiple Files into One File Using Bash

Suppose that our current directory has the following three text files:

  • teams1.txt
  • teams2.txt
  • teams3.txt

Each of these text files contain the names of various basketball teams.

We can use the cat command to view the contents of each file:

Suppose that we would like to concatenate the team names from each of these files into one single file named all_teams.txt.

We can use the following syntax to do so:

cat *.txt > all_teams.txt

The following screenshot shows how to use this syntax in practice:

Bash concatenate multiple files into one file

Notice that this new file named all_teams.txt contains the contents from all three text files.

By default, Bash concatenates the files in the following order: teams1.txt, teams2.txt, teams3.txt.

However, we can use the following syntax to instead concatenate the files in a different order:

cat teams2.txt teams3.txt teams1.txt > all_teams.txt

The following screenshot shows how to use this syntax in practice:

Bash concatenate files in specific order

The three text files have all been concatenated into a single file in the exact order that we specified.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Find Duplicate Lines in File
Bash: How to Check if File is Empty
Bash: How to Compare Two Files
Bash: How to Check if File Contains Specific String

Leave a Reply