How can I run a command on all files with the extension .gz?
Often a command already accepts several files as arguments, e.g.
zcat -- *.gz
On some systems, you would use gzcat instead of zcat. If neither is available, or if you don't care to play guessing games, just use gzip -dc instead.
The -- prevents a filename beginning with a hyphen from causing unexpected results.
If an explicit loop is desired, or if your command does not accept multiple filename arguments in one invocation, the for loop can be used:
# Bourne
for file in ./*.gz
do
echo "$file"
# do something with "$file"
doneTo do it recursively, use find:
# Bourne
find . -name '*.gz' -type f -exec do-something {} \;If you need to process the files inside your shell for some reason, then read the find results in a loop:
# Bash
while IFS= read -r file; do
echo "Now processing $file"
# do something fancy with "$file"
done < <(find . -name '*.gz' -print)This example uses ProcessSubstitution (see also FAQ #24), although a pipe may also be suitable in many cases. However, it does not correctly handle filenames that contain newlines. To handle arbitrary filenames, see FAQ #20.