How to Concatenate Multiple Files in Bash

MD Aminul Islam Feb 02, 2024
How to Concatenate Multiple Files in Bash

Sometimes we need to concatenate multiple files into a single file for various purposes. In Bash scripting, there is easy to do this task.

With the help of the Bash script, you can automate this task, and you need not do it manually by copying and pasting. This article will show how we can concatenate multiple files into a single file, and also, we are going to see examples and explanations to make the topic easier.

Concatenate Multiple Files in Bash

Suppose we have two text files, and we need to combine them into a single file. Our first text file contains the below content.

This is a text from the first file.

And our second file will contain the below contents.

This is a text from the second file.

Now, you can follow the example command for combining these two files below.

cat *.txt >> all.txt # output to all.txt

In the command above, * is for all. In the example above, we concatenate all the text files into a single file named all.txt.

When you execute the command, you will have a file named all.txt in your directory containing the below content.

This is a text from the first file. This is a text from the second file.

There is another version of this command. As shown in our example below, we used > instead of >>.

This single > will allow overwriting.

cat *.txt > all.txt # overwrites all.txt

If you have different filenames or combine only the specified file, you need to mention all the file names with the command. For this purpose, you can follow the example shared below.

cat file1 file2 file3 file4 file5 file6 > out.txt

All the files included with the command will be concatenated to a new file named out.txt.

All the codes used in this article are written in Bash. It will only work in the Linux Shell environment.

MD Aminul Islam avatar MD Aminul Islam avatar

Aminul Is an Expert Technical Writer and Full-Stack Developer. He has hands-on working experience on numerous Developer Platforms and SAAS startups. He is highly skilled in numerous Programming languages and Frameworks. He can write professional technical articles like Reviews, Programming, Documentation, SOP, User manual, Whitepaper, etc.

LinkedIn

Related Article - Bash Cat