如何删除大树中特定命名文件夹中具有特定扩展名的所有文件?

Nas*_*ser 6 find files

我有大树,里面有很多pdf文件。我想删除pdf这棵树中的文件,但只有那些pdf名为的子文件夹中的文件rules/There are other types of files inside rules/. 该rules/子文件夹没有其他的子文件夹。

例如,我有这棵树。“来源”以下的所有内容

  source/
         A/
            rules/*.pdf, *.txt, *.c,etc..
            etc/
         B/
            keep_this.pdf                
            rules/*.pdf
            whatever/
         C/ 
            D/
               rules/*.pdf
               something/
Run Code Online (Sandbox Code Playgroud)

等等。pdf到处都是文件,但我只想删除pdf名为文件夹中的所有文件,rules/而没有其他地方。

我想我需要使用

  cd source
  find  / -type d -name "rules"  -print0 | xargs -0 <<<rm *.pdf?? now what?>>>
Run Code Online (Sandbox Code Playgroud)

但是我不确定在获得所有命名的子文件夹列表后该怎么做 rules/

任何帮助表示赞赏。

在 Linux 薄荷上。

And*_*mes 8

我会find在另一个内部执行一个find。例如,我将执行此命令行以列出将被删除的文件:

$ find /path/to/source -type d -name 'rules' -exec find '{}' -mindepth 1 -maxdepth 1 -type f -iname '*.pdf' -print ';'
Run Code Online (Sandbox Code Playgroud)

然后,在检查列表后,我将执行:

$ find /path/to/source -type d -name 'rules' -exec find '{}' -mindepth 1 -maxdepth 1 -type f -iname '*.pdf' -print -delete ';'
Run Code Online (Sandbox Code Playgroud)


don*_*sti 5

使用支持扩展 globs 和 null globs 的外壳,例如zsh:

for d in ./**/rules/
do
set -- ${d}*.pdf(N)                               
(( $# > 0 )) && printf %s\\n $@
done
Run Code Online (Sandbox Code Playgroud)

或bash:

shopt -s globstar
shopt -s nullglob
for d in ./**/rules/
do
set -- "${d}"*.pdf
(( $# > 0 )) && printf %s\\n "$@"
done
Run Code Online (Sandbox Code Playgroud)

如果您对结果满意,请替换printf %s\\n为rm。


由于您使用的是 gnu/linux,您还可以运行:

find . -type f -regextype posix-basic -regex '.*/rules/[^/]*.pdf' -delete
Run Code Online (Sandbox Code Playgroud)

-delete如果要执行试运行,请删除。