Use bash to find first folder name that contains a string

后端 未结 3 1024
伪装坚强ぢ
伪装坚强ぢ 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: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)
    

提交回复
热议问题