Linux: How to Find Files and Tar them
This post will guide you how to find files and then archive all files into a tar ball with tar command in Linux. How to combine the tar command with find command in Linux.
Find Files and Tar Them
If you want to find files that match the pattern *.txt in a specific directory /home/devops/working, then archive all those files into a tarball. How to achieve it. You can use the find command to find all matching files, and passed all files into tar command to archive them. Just like the following command:
# find /home/devops/working/ -name "*.txt" -exec tar -rvf mytxt.tar {} \;
Or
# find /home/devops/working/ -name "*.txt" -print0 | tar -cvf ./mytxt.tar --null -T -
Or
# find /home/devops/working/ -name "*.txt" | xargs tar zcvf ./mytxt.tar.gz
Outputs:
devops@devops-osetc:~/working$ find /home/devops/working/ -iname "*.txt" -exec tar -rvf mytxt.tar {} \; tar: Removing leading `/' from member names /home/devops/working/fio3.txt tar: Removing leading `/' from member names /home/devops/working/fio2.txt tar: Removing leading `/' from member names /home/devops/working/fio1.txt devops@devops-osetc:~/working$ ls mytxt.tar mytxt.tar devops@devops-osetc:~/working$ find /home/devops/working/ -name "*.txt" -print0 | tar -cvf ./mytxt.tar --null -T - tar: Removing leading `/' from member names /home/devops/working/fio3.txt /home/devops/working/fio2.txt /home/devops/working/fio1.txt devops@devops-osetc:~/working$ ls mytxt.tar mytxt.tar devops@devops-osetc:~/working$ devops@devops-osetc:~/working$ find /home/devops/working/ -name "*.txt" | xargs tar zcvf ./mytxt.tar.gz tar: Removing leading `/' from member names /home/devops/working/fio3.txt /home/devops/working/fio2.txt /home/devops/working/fio1.txt devops@devops-osetc:~/working$ ls mytxt.tar.gz mytxt.tar.gz