Differences between revisions 8 and 9
Revision 8 as of 2010-04-27 13:46:51
Size: 1148
Editor: ip98-171-169-141
Comment:
Revision 9 as of 2010-07-30 14:32:06
Size: 1429
Editor: GreyCat
Comment: fixes. fixes are good.
Deletions are marked like this. Additions are marked like this.
Line 24: Line 24:
To do it recursively, you should use a loop, plus the [[UsingFind|find]] command: To do it recursively, use [[UsingFind|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:
Line 28: Line 35:
    while read file; do
        echo "$file"
        # do something with "$file"
    while IFS= read -r file; do
        echo "Now processing $file"
        # do something fancy with "$file"
Line 34: Line 41:
For more hints in this direction, see [[BashFAQ/020|FAQ #20]]. To see why the `find` command comes after the loop instead of before it, see [[BashFAQ/024|FAQ #24]]. This example uses ProcessSubstitution (see also [[BashFAQ/024|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 [[BashFAQ/020|FAQ #20]].

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"
    done

To 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.


CategoryShell

BashFAQ/015 (last edited 2015-03-05 00:30:34 by izabera)