使用 bash 查找包含字符串的第一个文件夹名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16344365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 23:39:28  来源:igfitidea点击:

Use bash to find first folder name that contains a string

bashshellfind

提问by dylanized

I would like to do this in Bash:

我想在 Bash 中这样做:

  • in the current directory, find the first folder that contains "foo" in the name
  • 在当前目录中,找到名称中包含“foo”的第一个文件夹

I've been playing around with the find command, but a little confused. Any suggestions?

我一直在玩 find 命令,但有点困惑。有什么建议?

回答by hek2mgl

You can use the -quitoption of find:

您可以使用以下-quit选项find

find <dir> -maxdepth 1 -type d -name '*foo*' -print -quit

回答by Adrian Frühwirth

pattern="foo"
for _dir in *"${pattern}"*; do
    [ -d "${_dir}" ] && dir="${_dir}" && break
done
echo "${dir}"

This is better than the other shell solution provided because

这比提供的其他 shell 解决方案更好,因为

  • it will be faster for huge directories as the pattern is part of the glob and not checked inside the loop
  • actually works as expected when there is no directory matching your pattern (then ${dir}will be empty)
  • it will work in any POSIX-compliant shell since it does not rely on the =~operator (if you need this depends on your pattern)
  • it will work for directories containing newlines in their name (vs. find)
  • 对于巨大的目录,它会更快,因为模式是 glob 的一部分,而不是在循环内检查
  • 当没有与您的模式匹配的目录时,实际上按预期工作(然后${dir}将为空)
  • 它可以在任何符合 POSIX 的 shell 中工作,因为它不依赖于=~操作符(如果你需要这取决于你的模式)
  • 它将适用于名称中包含换行符的目录(与find

回答by jm666

for example:

例如:

dir1=$(find . -name \*foo\* -type d -maxdepth 1 -print | head -n1)
echo "$dir1"

or (For the better shell solution see Adrian Frühwirth's answer)

或(有关更好的外壳解决方案,请参阅 Adrian Frühwirth 的回答)

for dir1 in *
do
    [[ -d "$dir1" && "$dir1" =~ foo ]] && break
    dir1=        #fix based on comment
done
echo "$dir1"

or

或者

dir1=$(find . -type d -maxdepth 1 -print | grep 'foo' | head -n1)
echo "$dir1"

Edited head -n1 based on @ hek2mgl comment

根据@ hek2mgl 评论编辑 head -n1

Next based on @chepner's comments

接下来基于@chepner 的评论

dir1=$(find . -type d -maxdepth 1 -print | grep -m1 'foo')

or

或者

dir1=$(find . -name \*foo\* -type d -maxdepth 1 -print -quit)