Merging Files in Unix
May 9, 2008 · Print This Article
You have multiple files in containing data in similar format and wanted to consolidate in a single file. This is usually the case if you have a daily log that you want to place an archive copy in a single file in weekly or in monthly, yearly.
The basic syntax of merging file is
-
cat <source file> >> <target file>
If you have more than 10 files to merge it is better to write a shell script that will loop through the files and merge in a file. The following is the code for merging the files in a folder into a single file.
-
#!/bin/sh
-
echo enter file name
-
read filename
-
-
for arg in `ls;`
-
do
-
echo $arg
-
cat $arg >> $filename
-
done
Lines 2 and 3 prompts the user for the filename of the file which will contain the consolidated contents of all the files in the current folder.
Lines 5 to 9 loops through the files in the current folder and merge the files to a single file.
Simplest File Merging
-
#!/bin/sh
-
echo enter file name
-
read source_filemask
-
read master_filename
-
-
cat $arg >> $filename
A simple file merging
-
cat $<filemask>*> $<filename>
Example
-
cat $Test*> $FinalTest.txt





Comments
Got something to say?