How to Combine Multiple Files Into One on Linux

  • by
In this post, I will introduce several ways to Combine files into one file. Suppose we have 4 files as followings:
[root@localhost ~]$ cat 1.txt
1. Database.
1. Database.
[root@localhost ~]$ cat 2.txt
2. Web.
2. Web.
[root@localhost ~]$ cat 3.txt
3. IT Architecture.
3. IT Architecture.
[root@localhost ~]$ cat 4.txt
4. Project.
4. Project.

  1. Vertical format: We can merge them by concatenating vertically.
  2. [root@localhost ~]$ cat 1.txt 2.txt 3.txt 4.txt
    1. Database.
    1. Database.
    2. Web.
    2. Web.
    3. IT Architecture.
    3. IT Architecture.
    4. Project.
    4. Project.
    [root@localhost ~]$ cat 1.txt 2.txt 3.txt 4.txt > all.txt

    Descendingly ordered combination: [root@localhost ~]$ cat 4.txt 3.txt 2.txt 1.txt
    4. Project.
    4. Project.
    3. IT Architecture.
    3. IT Architecture.
    2. Web.
    2. Web.
    1. Database.
    1. Database.

    If there’re too many files to be combined, you can use wild card to merge them. But you cannot control the order in this way. It’s always ordered by ascending-alphabetic filenames.
    [root@localhost ~]$ cat *.txt
    1. Database.
    1. Database.
    2. Web.
    2. Web.
    3. IT Architecture.
    3. IT Architecture.
    4. Project.
    4. Project.

    You can control the combination order by inline listing. For example, descending alphabetic order:
    [root@localhost ~]$ cat `ls -r *.txt`
    4. Project.
    4. Project.
    3. IT Architecture.
    3. IT Architecture.
    2. Web.
    2. Web.
    1. Database.
    1. Database.

    An ascending modified time order:
    [root@localhost ~]$ cat `ls -t *.txt`
    3. IT Architecture.
    3. IT Architecture.
    1. Database.
    1. Database.
    4. Project.
    4. Project.
    2. Web.
    2. Web.

  3. Horizontal format: we can merge them by pasting them horizontally.
  4. [root@localhost ~]$ paste 1.txt 2.txt 3.txt 4.txt
    1. Database.    2. Web. 3. IT Architecture.     4. Project.
    1. Database.    2. Web. 3. IT Architecture.     4. Project.
    [root@localhost ~]$ paste 1.txt 2.txt 3.txt 4.txt > all.txt

    Please note that,  the default delimiter of paste is a tab character between texts. You can change it into other characters (e.g. a white space or a new line) in this way:
    [root@localhost ~]$ paste 1.txt 2.txt 3.txt 4.txt -d ' '
    1. Database. 2. Web. 3. IT Architecture. 4. Project.
    1. Database. 2. Web. 3. IT Architecture. 4. Project.
    [root@localhost ~]$ paste 1.txt 2.txt 3.txt 4.txt -d 'n'
    1. Database.
    2. Web.
    3. IT Architecture.
    4. Project.
    1. Database.
    2. Web.
    3. IT Architecture.
    4. Project.

    You can also control the combination order introduced in the first approach.

Leave a Reply

Your email address will not be published. Required fields are marked *