Use bash to find first folder name that contains a string

后端 未结 3 978
伪装坚强ぢ
伪装坚强ぢ 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)
    0 讨论(0)
  • 2021-01-30 13:23

    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)

    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

    Next based on @chepner's comments

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

    or

    dir1=$(find . -name \*foo\* -type d -maxdepth 1 -print -quit)
    
    0 讨论(0)
  • 2021-01-30 13:24

    You can use the -quit option of find:

    find <dir> -maxdepth 1 -type d -name '*foo*' -print -quit
    
    0 讨论(0)
提交回复
热议问题