Use bash to find first folder name that contains a string

后端 未结 3 1027
伪装坚强ぢ
伪装坚强ぢ 2021-01-30 12:58

I would like to do this in Bash:

  • in the current directory, find the first folder that contains \"foo\" in the name

I\'ve been playing around with th

3条回答
  •  时光取名叫无心
    2021-01-30 13:19

    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

    • 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)

提交回复
热议问题