【问题标题】:search through a range of directories bash script搜索一系列目录 bash 脚本
【发布时间】:2010-12-27 12:31:58
【问题描述】:

我已经编写(尝试)了这个用于搜索一系列目录的小型 bash 脚本。

#!/bin/bash
shopt -s nullglob
for file in [ac]*/blarg
do 
   echo $file
   done

此脚本在以“a”到“c”开头的目录中搜索“blarg”。 它只深入一层。我怎样才能让它遍历它可能遇到的所有目录,而不仅仅是带有起始字母的目录的根目录。

另外,这个问题应该在 stackoverflow 上提问还是超级用户更合适?

谢谢

【问题讨论】:

  • 如果你的意思是'a'到'c',你的模式需要是[ac],而不仅仅是[ac]
  • 谢谢你,你是对的,先生。
  • 注意:benjamin button 和 1ch1g0 给出的答案都是正确的,可以做我需要的。但是因为我只能接受一个答案,所以我不得不选择benjamin button,因为他是第一个。抱歉 1ch1g0(我确实修改了你的答案)

标签: linux bash command-line scripting


【解决方案1】:

如果你有 Bash 4.0,你可以试试 globstar

#!/bin/bash
shopt -s nullglob
shopt -s globstar
for file in [ac]*/**/blarg
do 
   echo $file
done

【讨论】:

    【解决方案2】:

    在命令行上这将达到你的目的。那么为什么要使用脚本呢?

    find ./[ac]*/ -name "blarg"
    

    如果您仍然需要脚本:

    #!/bin/bash
    shopt -s nullglobi
    for file in `find ./[ac]*/ -name "blarg"`
    do
    echo $file
    done
    

    【讨论】:

    • 应该是./[ac]*/。如果文件名有空格,它也会失败。应该是find... | while read file...while read file...done < <(find ...)
    • 更接近,但使用 read 仍然会失败,路径名中包含换行符。 find [ac]*/ -name blarg -print0 | xargs -0 bash -c 'for file in "$@"; do …; done'
    • @Chris/Dennnis: while IFS= read -r -d $'\0' file; do...done < <(find ... -print0) 这将处理您可以扔给它的任何文件名。不需要 xargs。
    【解决方案3】:
    echo `find blarg`
    

    替换该行,您将在 [ac]* 下找到名为 blarg 的所有文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-21
      • 1970-01-01
      • 1970-01-01
      • 2016-06-27
      • 2013-07-14
      • 2013-05-09
      • 2011-05-11
      • 1970-01-01
      相关资源
      最近更新 更多