How to find specific file types and tar them?

8,324

Solution 1

Each of your two approaches was close to working, but each had a distinct problem.

In your first approach you try to pipe a list of files to tar. If you want tar to read the list of files from standard input then you have to use the -T/--files-from and - options, e.g.

find -name '*.png' -print0 | tar -cvf backup.tar --null -T - 

For a reference, see the official documentation:

NOTE: The use of the -print0 and --null flags should ensure that this also handles filenames which include whitespace.

In your second approach you try to run tar via xargs, but you're using the "create" option (--create / -c). If you use the "create" option with xargs or in a for-loop, then it will overwrite the archive after every iteration. Instead, try using either the "append" option (-a / --append) or the "update" option (-u / --update), e.g.:

find -name "*.png" -exec tar -uvf backupp.tar {} \;

This will append files to the archive after each iteration instead of over-writing it.

Either way, once you're done you can use the "list" option (--list / -t) to view the contents of the archive and verify that everything worked as expected:

tar tf backupp.tar

Solution 2

You can simply use the wildcard

tar -cvf backup.tar *.png

or by using find

find -name "*.png" | tar -cvf backup.tar -T -

the -T option gets the file name from FILE which in this case is stdin -

Share:
8,324

Related videos on Youtube

HabibieND
Author by

HabibieND

Updated on September 18, 2022

Comments

  • HabibieND
    HabibieND almost 2 years

    It seems I've got a problem. I've got some different file types in my current directory, and I want to just tar the .png files. I started with this:

    find -name "*.png" | tar -cvf backupp.tar
    

    It wouldn't work because I didn't specify which files, so looking on how others did it, I added xargs:

    find -name "*.png" | xargs tar -cvf backupp.tar
    

    It did work this time, and backupp.tar file was created, but here is the problem. I can't seem to extract it. Whenever I type:

    tar -xvf backupp.tar
    

    Nothings happens. I've tried changing chmod and sudo, but nothing gives in.

    So, did I type the wrong command completely or is there somethings I just missed?