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

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


当前回答

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

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
}

其他回答

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

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 /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

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

#!/usr/bin/zsh

for file in /tmp/**/*
do
    echo $file
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