Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use bash to find first folder name that contains a string

Tags:

find

bash

shell

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 the find command, but a little confused. Any suggestions?

like image 527
dylanized Avatar asked May 02 '13 17:05

dylanized


People also ask

How do I find a folder in Bash?

In order to check if a directory exists in Bash, you have to use the “-d” option and specify the directory name to be checked.

How do I get the first letter of a string in Bash?

To access the first character of a string, we can use the (substring) parameter expansion syntax ${str:position:length} in the Bash shell. position: The starting position of a string extraction.

How do I search for a string in a folder?

Finding text strings within files using grep-r – Recursive search. -R – Read all files under each directory, recursively. Follow all symbolic links, unlike -r grep option. -n – Display line number of each matched line.


2 Answers

You can use the -quit option of find:

find <dir> -maxdepth 1 -type d -name '*foo*' -print -quit 
like image 195
hek2mgl Avatar answered Oct 11 '22 12:10

hek2mgl


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)
like image 28
Adrian Frühwirth Avatar answered Oct 11 '22 11:10

Adrian Frühwirth