我需要递归地遍历一个目录,并删除所有扩展名为.pdf和.doc的文件。我设法递归地循环通过一个目录,但不设法过滤与上述文件扩展名的文件。

我目前的代码

#/bin/sh

SEARCH_FOLDER="/tmp/*"

for f in $SEARCH_FOLDER
do
    if [ -d "$f" ]
    then
        for ff in $f/*
        do      
            echo "Processing $ff"
        done
    else
        echo "Processing file $f"
    fi
done

我需要帮助来完成代码,因为我没有得到任何地方。


当前回答

下面的函数将递归遍历\home\ubuntu目录(ubuntu下的整个目录结构)中的所有目录,并在else块中应用必要的检查。

function check {
        for file in $1/*      
        do
        if [ -d "$file" ]
        then
                check $file                          
        else
               ##check for the file
               if [ $(head -c 4 "$file") = "%PDF" ]; then
                         rm -r $file
               fi
        fi
        done     
}
domain=/home/ubuntu
check $domain

其他回答

这并不能直接回答你的问题,但是你可以用一句话来解决你的问题:

find /tmp \( -name "*.pdf" -o -name "*.doc" \) -type f -exec rm {} +

一些版本的find (GNU, BSD)有一个-delete操作,你可以使用它来代替调用rm:

find /tmp \( -name "*.pdf" -o -name "*.doc" \) -type f -delete

下面的函数将递归遍历\home\ubuntu目录(ubuntu下的整个目录结构)中的所有目录,并在else块中应用必要的检查。

function check {
        for file in $1/*      
        do
        if [ -d "$file" ]
        then
                check $file                          
        else
               ##check for the file
               if [ $(head -c 4 "$file") = "%PDF" ]; then
                         rm -r $file
               fi
        fi
        done     
}
domain=/home/ubuntu
check $domain

对于bash(自版本4.0起):

shopt -s globstar nullglob dotglob
echo **/*".ext"

这是所有。 拖尾扩展”。在这里选择具有该扩展名的文件(或dirs)。

选项globstar激活**(递归搜索)。 选项nullglob在不匹配文件/dir时删除*。 选项dotglob包含以点开始的文件(隐藏文件)。

注意,在bash 4.3之前,**/也会遍历到目录的符号链接,这是不可取的。

下面是一个使用shell (bash)的例子:

#!/bin/bash

# loop & print a folder recusively,
print_folder_recurse() {
    for i in "$1"/*;do
        if [ -d "$i" ];then
            echo "dir: $i"
            print_folder_recurse "$i"
        elif [ -f "$i" ]; then
            echo "file: $i"
        fi
    done
}


# try get path from param
path=""
if [ -d "$1" ]; then
    path=$1;
else
    path="/tmp"
fi

echo "base path: $path"
print_folder_recurse $path

Find就是为这个设计的。

find /tmp -name '*.pdf' -or -name '*.doc' | xargs rm