You can also use cat commands for multiple operations, such as creating single or multiple files, viewing their contents, merging files, and displaying the output to a screen. It can even redirect these contents to files. If you also want to know the approach to combining text files, then don’t worry. In this guide, you will get to know about the ways to combine text files in Linux.
How To Combine Text Files in Linux
First, let’s find all the available options in the cat command. Then execute the following command:
Let’s begin with an example where you want to combine f1.txt, f2.txt, and f3.txt files into f4.txt. Using the following command, you can accomplish the task:
In case you don’t want to overwrite the f4.txt file, use the following command:
As you can see in the previous images, there is a massive difference in the result of both commands.
You can use the following cat command to view the file’s contents without opening it:
You can use the cat command, followed by the pipe command (|) and the sort command to sort the combined text files in an ordered list pattern.
After that, use the output redirection symbol (>) with the file’s name into which the combined text is to be copied. After that, all the lines of text in the result file will get sorted in alphabetical order. The command should be:
You can view the contents of a file with line numbers. Use -n followed by the name of the file as:
If you want to combine multiple large files, then instead of specifying each file’s name to be concatenated, use the wildcards to identify these files, followed by an output redirection symbol.
Hence, it is possible to concatenate all the files in the current directory using an asterisk (*) symbol wildcard as:
We can use the pipe symbol and the echo command that will feed all the files in the current directory to the cat command as:
The Linux operating system provides a variety of commands to combine text files into one file in an organized way. In this detailed guide, we have used different techniques to combine two text files into one file alphabetically or numerically utilizing the cat command. The cat command can be handy when combined with another command in different situations. We hope this guide helped you understand the straightforward approach to combining text files in Linux.