Find files and tar them (with spaces)

后端 未结 10 1685
北海茫月
北海茫月 2020-11-29 15:35

Alright, so simple problem here. I\'m working on a simple back up code. It works fine except if the files have spaces in them. This is how I\'m finding files and adding th

相关标签:
10条回答
  • 2020-11-29 16:24

    Would add a comment to @Steve Kehlet post but need 50 rep (RIP).

    For anyone that has found this post through numerous googling, I found a way to not only find specific files given a time range, but also NOT include the relative paths OR whitespaces that would cause tarring errors. (THANK YOU SO MUCH STEVE.)

    find . -name "*.pdf" -type f -mtime 0 -printf "%f\0" | tar -czvf /dir/zip.tar.gz --null -T -
    
    1. . relative directory

    2. -name "*.pdf" look for pdfs (or any file type)

    3. -type f type to look for is a file

    4. -mtime 0 look for files created in last 24 hours

    5. -printf "%f\0" Regular -print0 OR -printf "%f" did NOT work for me. From man pages:

    This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use '\0' as a terminator than to use newline, as file names can contain white space and newline characters.

    1. -czvf create archive, filter the archive through gzip , verbosely list files processed, archive name

    Edit 2019-08-14: I would like to add, that I was also able to use essentially use the same command in my comment, just using tar itself:

    tar -czvf /archiveDir/test.tar.gz --newer-mtime=0 --ignore-failed-read *.pdf
    

    Needed --ignore-failed-read in-case there were no new PDFs for today.

    0 讨论(0)
  • 2020-11-29 16:36

    Use this:

    find . -type f -print0 | tar -czvf backup.tar.gz --null -T -
    

    It will:

    • deal with files with spaces, newlines, leading dashes, and other funniness
    • handle an unlimited number of files
    • won't repeatedly overwrite your backup.tar.gz like using tar -c with xargs will do when you have a large number of files

    Also see:

    • GNU tar manual
    • How can I build a tar from stdin?, search for null
    0 讨论(0)
  • 2020-11-29 16:36

    Try running:

        find . -type f | xargs -d "\n" tar -czvf backup.tar.gz 
    
    0 讨论(0)
  • 2020-11-29 16:36

    Another solution as seen here:

    find var/log/ -iname "anaconda.*" -exec tar -cvzf file.tar.gz {} +
    
    0 讨论(0)
提交回复
热议问题