找出不使用递归的方法

284

是否有可能以某种方式使用find命令,使其不会递归到子目录中?例如:

DirsRoot
  |-->SubDir1
  |    |-OtherFile1
  |-->SubDir2
  |    |-OtherFile2
  |-File1
  |-File2

那么像 find DirsRoot --do-not-recurse -type f 这样的命令会得到只有 File1, File2 两个文件的结果吗?

4个回答

435

根据你当前的命令结构,我认为你可以使用 -maxdepth 1 选项来获得你想要的结果。如果不行,你可以尝试查看 findman page

相关条目(方便起见):

-maxdepth levels
          Descend at most levels (a non-negative integer) levels of direc-
          tories below the command line arguments.   `-maxdepth  0'  means
          only  apply the tests and actions to the command line arguments.

你的选择基本可以分为:

# Do NOT show hidden files (beginning with ".", i.e., .*):
find DirsRoot/* -maxdepth 0 -type f

或者:

#  DO show hidden files:
find DirsRoot/ -maxdepth 1 -type f

1
对于楼主的例子,我认为应该是“-maxdepth 1”? - Paul R
3
对我来说,-maxdepth 0 没有显示 任何 文件,但 -maxdepth 1 的表现如预期一样,包括显示隐藏文件。 - Srini
3
请注意 find DirsRoot/* -maxdepth 0 -type f 中的 *。如果您省略它,将不会显示任何文件。 - mapeters
@mook,谢谢,但是我不记得我遇到这个问题的原始上下文了,哈哈。 - Srini
使用“*”来省略隐藏文件,如果没有找到任何内容,则会显示错误。我猜你可以将stderr重定向到/dev/null,但这可能会掩盖其他问题。还不确定这是否真正有用作为一行解决方案。 - Bill Gale
显示剩余2条评论

37

我相信您正在寻找-maxdepth 1


18

如果您需要符合POSIX标准的解决方案:

cd DirsRoot && find . -type f -print -o -name . -o -prune

-maxdepth 不是符合POSIX标准的选项。


谢谢您提供的解决方案,但是这个命令不能简化为 find DirsRoot/* -type f -prune 吗? - dokaspar
@dokaspar 真的是个好问题!(顺便说一下,你忘记在 -prune 前插入“-o”了)答案是否定的。要完全理解为什么它不能被简化,只需在发出 find DirsRoot/* -type f -o -prune 命令之前发出 set -x 命令,你就会立即看到它。根本原因是 shell 扩展 DirsRoot/* 表达式的限制。 - sqr163
无法在CentOS上工作,输出仍然进行完整递归!!!正确的命令是find . -name . -o -prune - Reishin
在Solaris上,保持DirsRoot作为所需路径,您不需要cd; 相反,您可以使用以下命令:find DirsRoot/. -type f -print -o -name . -o -prune - spioter

5

使用find命令中的-maxdepth选项可以实现。

find /DirsRoot/* -maxdepth 1 -type f

来自手册

man find

-maxdepth levels

最多在起始点以下的目录层级(一个非负整数)中下降levels层。

-maxdepth 0

仅对起始点本身应用测试和操作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接