我需要递归地遍历一个目录,并删除所有扩展名为.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

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


当前回答

下面的代码将递归地遍历给定目录并列出所有内容:

for d in /home/ubuntu/*; 
do 
    echo "listing contents of dir: $d"; 
    ls -l $d/; 
done

其他回答

这个方法很好地处理了空格。

files="$(find -L "$dir" -type f)"
echo "Count: $(echo -n "$files" | wc -l)"
echo "$files" | while read file; do
  echo "$file"
done

编辑,逐个修复

function count() {
    files="$(find -L "$1" -type f)";
    if [[ "$files" == "" ]]; then
        echo "No files";
        return 0;
    fi
    file_count=$(echo "$files" | wc -l)
    echo "Count: $file_count"
    echo "$files" | while read file; do
        echo "$file"
    done
}

只做

find . -name '*.pdf'|xargs rm

Find就是为这个设计的。

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

作为mouviciel回答的后续,您还可以将其作为for循环来执行,而不是使用xargs。我经常发现xargs很麻烦,特别是当我需要在每次迭代中做一些更复杂的事情时。

for f in $(find /tmp -name '*.pdf' -or -name '*.doc'); do rm $f; done

正如许多人所评论的那样,如果文件名中有空格,这将失败。您可以通过临时将IFS(内部字段分隔符)设置为换行符来解决这个问题。如果有通配符\[?文件名中的*。您可以通过暂时禁用通配符展开(globbing)来解决这个问题。

IFS=$'\n'; set -f
for f in $(find /tmp -name '*.pdf' -or -name '*.doc'); do rm "$f"; done
unset IFS; set +f

如果文件名中有换行符,那么这也行不通。你最好使用基于xargs的解决方案:

find /tmp \( -name '*.pdf' -or -name '*.doc' \) -print0 | xargs -0 rm

(这里需要转义的括号,以使-print0应用于两个或子句。)

GNU和*BSD find也有一个-delete操作,看起来像这样:

find /tmp \( -name '*.pdf' -or -name '*.doc' \) -delete

如果可以更改用于运行该命令的shell,则可以使用ZSH来完成该工作。

#!/usr/bin/zsh

for file in /tmp/**/*
do
    echo $file
done

这将递归循环遍历所有文件/文件夹。