Removing and Adding Files to Existing Tar Archive

Removing and adding files to existing tar archive

If you are looking to remove and add files to existing tar archive, here are some useful steps we recommend for implementing the changes.

1) How to remove a single file from tar file

We need to create a tar file, for that first we need to touch some files

# touch  textfile{1..4}.txt

Now we can create tar file using tar command

# tar -cvf nixtree.tar textfile{1..4}.txt

Which creates the tar file “nixtree.tar” with the files file1.txt to file4.txt
To test the files in a tar file you can use “-t” switch with tar command.

# tar -tf nixtree.tar
textfile1.txt
textfile2.txt
textfile3.txt
textfile4.txt

We can use the “–delete” switch with tar command to remove files from already created tar file.

# tar --delete -f nixtree.tar  textfile1.txt

This command will remove “textfile1.txt” from the tar archive “nixtree.tar”

now see that tar file again

# tar -tf nixtree.tar
textfile2.txt
textfile3.txt
textfile4.txt

Also we can remove file from tar file using pattern matching .see below

2) Pattern match – Removing files using “–wildcards” options

# tar --wildcards --delete -f nixtree.tar 'textfile*'

This will remove all files starting with textfile. Which means the above tar file will be empty

3) Adding a file or directory to the existing tar file

You can add a file to a existing tar file  with ‘r’ option

# tar -rvf nixtree.tar newfile.txt

4) Adding directory to the existing tar file also the same

# tar -rvf nixtree.tar /new-directory

5) Extracting specific files  and directory from tar file

You can now extract the file  ‘textfile4.txt’ from the archive file ‘nixtree.tar’ like this:

# tar --extract --file=nixtree.tar  textfile4.txt

6) Extract a directory  from nixtree.tar:

# tar --extract --file=nixtree.tar directoryname

7) Compressing a folder (tar) without its containing directory in the foldername

# tar -zcvf nixtree.tar.gz -C /path/to/foldername_tocompress

8) Untar tar file to specific location

# tar -xvf nixtree.tar -C /path/to/untar/files/to/specific/directory

Tar Usage and Options

c – create a archive file.
x – extract a archive file.
v – show the progress of archive file.
f – filename of archive file.
t – viewing content of archive file.
r – append or update files or directories to existing archive file.
wildcards – Specify pattern in unix tar command.

We hope this helps you in understanding the ways to remove and add files to the existing tar archive.

Talk to our Server Helpdesk Support experts to help you resolve issues related to all Linux Server Management queries and more!

Facebook Comments