【问题标题】:How to exclude subdirectories of a specific directory from find command?如何从 find 命令中排除特定目录的子目录?
【发布时间】:2023-04-02 01:20:01
【问题描述】:

我正在尝试获取可以通过管道传输到wc -l 的文件列表以获取所有文件的字数(不直接使用wc,因此我可以在使用命令之前过滤文件列表)。

我的目录结构是这样的:

- folder
   - file.php
   - file2.html
   - file3.php
   - folder1
   - folder2a
   - folder3b
   - folder4
- file.php
- file2.php

我想排除我的find 中的某些目录,主要是库和其他我没有制作的东西。我可以像这样手动完成:

find /var/www/html/ -type f -not -path "/var/www/html/folder/folder1" -not -path "/var/www/html/folder/folder2a"

但是,必须明确指定所有文件夹很烦人,而且列表也可能随时更改。我尝试使用/*/** 进行模式匹配,但这也不起作用。 有没有办法让我的 find 命令中的这些“非”之一可以排除特定目录的所有子目录,但排除该目录本身?(包括它的文件,但不包括它的任何子目录)?

这是一个直观的猜测:

find /var/www/html -not -path '/var/www/html/someotherbadfolder' -type f \( ! -path "/var/www/html/folder" -maxdepth 1 \)

但即使是find 也会抱怨:

find: warning: you have specified the -maxdepth option after a non-option argument -not, but options are not positional (-maxdepth affects tests specified before it as well as those specified after it).  Please specify options before other arguments.

所以看来maxdepth 无法在一个操作中合并。

有很多关于排除特定子目录的问答,但通常不是特定子目录中的任何子目录。

我能够使用-maxdepth 1 使其在单个目录中工作,但问题是这是一个较大命令的排除部分,并且在我运行完整命令后就不起作用了。潜在地,我可能需要排除特定子目录以及其他几个特定子目录中的任何子目录。

【问题讨论】:

  • find /var/www/html -type d -path '/var/www/html/folder/*' -prune -o -type f -print

标签: bash shell unix find


【解决方案1】:

只需查找:

find /var/www/html -type f -not -path '/var/www/html/folder/*/*'

原答案:

find 的输出可能是grep -v

find /var/www/html/ -type f | grep -v "/var/www/html/folder/.*/" | wc -l

【讨论】:

  • 这太完美了!我只需要在wc 之前添加xargs,它就完成了我想要的。我想我可以多次管道,对于每个需要排除子目录的文件夹一次,并排除其他子目录作为查找的一部分。
【解决方案2】:

假设您专门寻找文件(即不是目录):

find /var/www/html -type f -not -path "/var/www/html/folder/*/*"

那是因为:

  • 直接位于/var/www/html/folder 下的文件不是目录,因此它们与-path 子句不匹配。
  • /var/www/html/folder 下的目录与-type f 不匹配。
  • /var/www/html/folder 子目录下的文件必须在路径中包含额外的/,因此它们与-path 表达式匹配。

【讨论】:

  • 你是对的,我没有测试过这个案例,答案是固定的。
猜你喜欢
  • 2011-05-11
  • 2021-10-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-14
  • 2016-05-22
  • 2012-12-25
  • 2012-11-07
  • 2013-08-05
相关资源
最近更新 更多