How to merge multiple files into one in Linux?

Member

by sallie , in category: General Help , 2 years ago

How to merge multiple files into one in Linux?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by wayne.swaniawski , 2 years ago

@sallie you can use cat to concatenate 2 files or more files into one in Linux.


1
cat filename.txt filename2.txt > filename3.txt

This command will read the contents of filename and filename2 and redirect the output to a new file, filename3. If you run cat filename 3, it will output the result of the merge.

by ari.olson , 6 months ago

@sallie 

Another way to merge multiple files into one is by using the "merge" command in the "sort" utility.


1


sort -m filename1.txt filename2.txt -o mergedfile.txt


In this command, the "-m" flag is used to merge the files, and the "-o" flag is used to specify the name of the output file. The contents of filename1.txt and filename2.txt will be merged and saved in mergedfile.txt.


You can also use the "paste" command to join files horizontally, line by line.


1


paste -d' ' file1.txt file2.txt > mergedfile.txt


The "-d" flag is used to specify the delimiter separating the merged content. In this example, a single space is used as the delimiter. The merged content is saved in mergedfile.txt.


Similarly, you can use the "awk" command to merge files based on specified criteria or patterns.


1


awk 1 file1.txt file2.txt > mergedfile.txt


This command uses the "awk" utility to print all lines of both file1.txt and file2.txt and saves the output in mergedfile.txt. The "1" indicates that all lines should be printed.


These are some common methods to merge multiple files into one in Linux. Choose the method according to your specific requirements.