简体   繁体   中英

Find and tar for each file in Linux

I have a list of files with different modification times, 1_raw,2_raw,3_raw... I want to find files that are modified more than 10 days ago and zip them to release disk space. However, the command:

find . -mtime +10 |xargs tar -cvzf backup.tar.gz

will create a new file backup.tar.gz

What I want is to create a tarball for each file, so that I can easily unzip each of them when needed. After the command, my files should become: 1_raw.tar.gz, 2_raw.tar.gz, 3_raw.tar.gz...

Is there anyway to do this? Thanks!

Something like this is what you are after:

find . -mtime +10 -type f -print0 | while IFS= read -r -d '' file; do
   tar -cvzf "${file}.tar.gz" "$file"
done

The -type f was added so that it doesn't also process directories, just files.

This adds a compressed archive of each file that was modified more than 10 days ago, in all subdirectories, and places the compressed archive next to its respective unarchived version (in the same folder). I assume this is what you wanted.


If you didn't need to handle whitespaces in the path, you could do with simply:

for f in $(find . -mtime +10 -type f) ; do
  tar -cvzf "${f}.tar.gz" "$f"
done

Simply, try this

$ find . -mtime +10 | xargs -I {} tar czvf {}.tar.gz {}

Here, {} indicates replace-str -I replace-str Replace occurrences of replace-str in the initial-arguments with names read from standard input. Also, unquoted blanks do not terminate input items; instead the separator is the newline character. Implies -x and -L 1. https://linux.die.net/man/1/xargs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM