how do I tar.gz everything apart from jpg/gif/png/wmv/flv/zips, recursively, via the Unix shell?

migrated from stackoverflow.com Dec 10 '09 at 0:47

This question came from our site for professional and enthusiast programmers.


Use the --exclude option:

tar czvf myarchive.tar.gz --exclude=\*.{jpg,gif,png,wmv,flv,tar.gz,zip} rootdir
  • Just make sure you're running gnu tar, otherwise this flag won't exist. On solaris you can specify an exclude file though. – Darren Hall Dec 10 '09 at 1:07
find -type f -a ! \( \
                     -name '*.jpg' -o \
                     -name '*.gif' -o \
                     -name '*.png' -o \
                     -name '*.wmv' -o \
                     -name '*.flv' -o \
                     -name '*.tar.gz' -o \
                     -name '*.zip' \) \
 | xargs tar rvfz files.tgz

I used multilple lines to make it easier to edit later in case you made this into a shell script or shell function.

I use the -r flag for tar in case the number of files exceeds 1 call into xargs. This way you can't exceed the argument buffer for tar.


  find ./ -type f | egrep -v "\.(jpg|gif|png|wmv|flz|zips)$" | xargs tar -czf filename.tgz
  • 1
    you may have had a typo with "zips", so edit accordingly – Kevin Lochner Dec 10 '09 at 0:57
  • 1
    Do you want to be a $ at the end there? Won't your egrep filter out jpg.txt? – Suppressingfire Dec 10 '09 at 1:09
  • 2
    tar (c)reate + xargs can be dangerous if your arg length is long enough that tar is called twice. – Darren Hall Dec 10 '09 at 1:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy