【问题标题】:find without recursion不递归查找
【发布时间】:2011-04-24 22:20:27
【问题描述】:

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

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

find DirsRoot --do-not-recurse -type f 这样的结果只会是File1, File2

【问题讨论】:

    标签: unix find shell


    【解决方案1】:

    我想你会根据你当前的命令结构使用-maxdepth 1 选项得到你想要的。如果没有,您可以尝试查看man pagefind

    相关条目(为方便起见):

    -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
    

    【讨论】:

    • 对于 OP 的例子,我认为这需要是 -maxdepth 1 ?
    • @Paul R:实际上,这取决于他想要如何处理隐藏文件,但我仍然修改了我的答案。对于他的例子1 可能是他想要的。
    • 对我来说,-maxdepth 0 没有显示 任何 文件,但 -maxdepth 1 正在按预期工作,同时显示隐藏文件。
    • @BruceWayne 请注意find DirsRoot/* -maxdepth 0 -type f 中的*。如果您忽略它,它将不会显示任何文件。
    • @mook,谢谢,但我不记得我遇到这个问题的原始背景,哈哈。
    【解决方案2】:

    我相信你正在寻找-maxdepth 1

    【讨论】:

      【解决方案3】:

      如果您正在寻找符合 POSIX 标准的解决方案:

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

      -maxdepth 不是 POSIX 兼容选项。

      【讨论】:

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

      是的,可以在 find 命令中使用 -maxdepth 选项

      find /DirsRoot/* -maxdepth 1 -type f
      

      来自手册

      man find

      -maxdepth 级别

      在起点以下的目录的大多数级别(非负整数)级别下降。

      -maxdepth 0

      表示仅将测试和操作应用于起点本身。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-07-17
        • 2015-12-16
        • 2011-05-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多