Tar multiple files in UNIX

Suppose you have a list of Files that you need to tar.All the files name are present in a single file.
eg. In one file FileList.txt you have several files : File1 , File2 ,File3 etc.

FileList.txt looks like :
File1.txt
File2.txt
File3.txt
File4.txt
File5.txt
and you want a TAR file which is having all these files i.e. File1.txt – File5.txt.
The easiest method I know to do is :

tr '\n' ' ' FileList.txt FileList1.txt
mv FileList1.txt FileList.txt
sed '${/^$/!s/$/\ /;}' FileList.txt
tar cvf MyTar.tar `head -1 FileList.txt`

That is it.Just these four simple lines can do the job perfectly.
Now let us see what each line is doing here.

First line is :

 tr '\n' ' ' FileList.txt FileList1.txt

This line is changing all the new lines to space in FileList.txt and saving the output to FileList1.txt.We are doing this in order to transpose our filenames in FileList.txt
After running this line , Content of our FileList.txt will look like :
File1.txt File2.txt File3.txt File4.txt File5.txt

You will soon understand why are we doing this.
Now coming to second line :

mv FileList1.txt FileList.txt

This command is simply changing my FileList1.txt to my original file FileList.txt and FileList1.txt will be gone.
Now coming to third line which is :

sed '${/^$/!s/$/\ /;}' FileList.txt


This command will simply remove any blank line at the end.We are doing this in order to save a possible error which may come while taring files.

Last line is

tar cvf MyTar.tar `head -1 FileList.txt`

This command will get list of files from FileList.txt and send it to TAR.Hence making tar files with all the the filename present in FileList.txt.MyTar.tar is the name of the tar created.

Leave a Reply

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