Concatenating Text Files into a Single File in Linux
In this quick tutorial, we’ll see how to concatenate files into a single file.
2. Introducing cat Command
Let’s say we have two text files, A.txt and B.txt.
Content from file A.
Content from file B.
Now, let’s merge these files into file C.txt:
cat A.txt B.txt > C.txt
The cat command concatenates files and prints the result to the standard output. Hence, to write the concatenated output to a file, we’ve used the output redirection symbol ‘>’. This sends the concatenated output to the file specified.
The above script will create the file C.txt with the concatenated contents:
Content from file A. Content from file B.
Note that if the file C.txt already exists, it’ll simply be overwritten.
Sometimes, we might want to append the content to the output file rather than overwriting it. We can do this by using the double output redirection symbol >>:
cat A.txt B.txt >> C.txt
The examples above concatenate two files. But, if we want to concatenate more than two, we specify all these files one after another:
cat A.txt B.txt C.txt D.txt E.txt > F.txt
This’ll concatenate all the files in the order specified.
3. Concatenating Multiple Files Using a Wildcard
If the number of files to be concatenated is large, it is cumbersome to type in the name of each file. So, instead of specifying each file to be concatenated, we can use wildcards to specify the files.
For example, to concatenate all files in the current directory, we can use the asterisk(*) wildcard:
cat *.txt > C.txt
We have to be careful while using wildcards if the output file already exists — if the wildcard specified includes the output file, we’ll get an error:
cat: C.txt: input file is output file
It’s worth noting that when using wildcards, the order of the files isn’t predictable. Consequently, we’ll have to employ the method we saw in the previous section if the order in which the files are to be concatenated is important.
Going a step further, we can also use pipes to feed the contents of the input files to the cat command. For example, we can echo the contents of all files in the current directory and feed it’s output to cat:
echo *.txt | xargs cat > D.txt