How to find and tar files into a tar ball

Iwould like to find all documents file *.doc and create a tarball of those files and store in /nfs/backups/docs/file.tar. Is it possible to find and tar files on a Linux or Unix-like system?

The find command used to search for files in a directory hierarchy as per given criteria. The tar command is an archiving utility for Linux and Unix-like system to create tarballs.
How to find and tar files on linux unix
Let us see how to combine tar command with find command to create a tarball in a single command line option.

Find command

The syntax is:
find /path/to/search -name "file-to-search" -options
## find all Perl (*.pl) files ##
find $HOME -name "*.pl" -print
## find all *.doc files ##
find $HOME -name "*.doc" -print
## find all *.sh (shell scripts) and run ls -l command on it ##
find . -iname "*.sh" -exec ls -l {} +

Sample outputs from the last command:

Tar command

To create a tar ball of /home/vivek/projects directory, run:
$ tar -cvf /home/vivek/projects.tar /home/vivek/projects

Combining find and tar commands

The syntax is:
find /dir/to/search/ -name "*.doc" -exec tar -rvf out.tar {} ;
find /dir/to/search/ -name "*.doc" -exec tar -rvf out.tar {} +
For example:
find $HOME -name "*.doc" -exec tar -rvf /tmp/all-doc-files.tar "{}" ;
find $HOME -name "*.doc" -exec tar -rvf /tmp/all-doc-files.tar "{}" +
Where, find command options:
  • -name "*.doc" : Find file as per given pattern/criteria. In this case find all *.doc files in $HOME.
  • -exec tar ... : Execute tar command on all files found by the find command.
Where, tar command options:
  • -r : Append files to the end of an archive. Arguments have the same meaning as for -c option.
  • -v : Verbose output.
  • -f : out.tar : Append all files to out.tar file.
It is also possible to pipe output of the find command to the tar command as follows:
find $HOME -name "*.doc" -print0 | tar -cvf /tmp/file.tar --null -T -
The -print0 option passed to the find command deals with special file names. The –null and -T – option tells the tar command to read its input from stdin/pipe. It is also possible to use the xargs command:
find $HOME -type f -name "*.sh" | xargs tar cfvz /nfs/x230/my-shell-scripts.tgz
See the following man pages for more info:
$ man tar
$ man find
$ man xargs
$ man bash

Trả lời

Close Menu