简体   繁体   中英

How to gzip all files in all sub-directories in bash

I want to iterate among sub directories of my current location and gzip each file seperately. For zipping files in a directory, I use

for file in *; do gzip "$file"; done

but this can just work on current directory and not the sub directories of the current directory. How can I rewrite the above statements so that It also zips the files in all subdirectories?

No need for loops or anything more than find and gzip :

find . -type f ! -name '*.gz' -exec gzip "{}" \;

This finds all regular files in and below the current directory whose names don't end with the .gz extension (that is, all files that are not already compressed). It invokes gzip on each file individually.


Edit, based on comment from user unknown :

The curly braces ( {} ) are replaced with the filename, which is passed directly, as a single word, to the command following -exec as you can see here:

$ touch foo
$ touch "bar baz"
$ touch xyzzy
$ find . -exec echo {} \;

./foo
./bar baz
./xyzzy

我更喜欢gzip -r ./它做同样的事情但更短。

find . -type f | while read file; do gzip "$file"; done

I can't comment on the top post (yet...), but I read in the man pages of "find" that -execDir is safer than -exec because the command is done in the subdirectory where the match is found, rather than the parent directory where "find" is ran from.

If anyone would like to use a regex with to locate specific files in a subdirectory to zip, I'd recommend using

find ./ -type f -name 'addRegexHere' -execdir gzip -k "{}" \;

if you don't need regex's, stick with the recursive gzip call above (or below, if I gain any traction haha)

source

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