dylanized dylanized - 1 year ago 123
Bash Question

Use bash to find a folder name that contains a string

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?

EDIT: awesome suggestions, but how can I store the result in a variable?

EDIT #2: damn you guys are great. But one more question - how can I pass in a variable for "foo" into the subshell? (Not necessary in the suggestion that doesn't use subshell, I'll try that for now.) THANK YOU

Answer Source

Update For travellers from google. The best would be using the following command line which is using the head command, which is intended for that, to display only the first line (as answered by @jm666) :

find <dir> -maxdepth 1 -type d -name '*foo*'| head -n1

However, here comes my former awk attempt:

find <dir> -maxdepth 1 -type d -name '*foo*'| awk '{if(NR==1) print}'

what can be simplified to (thanks @Kevin):

find <dir> -maxdepth 1 -type d -name '*foo*'| awk 'NR==1'

It finds all folders in the current folder (not recursively) and uses awk to print only the first line of the result to stdout

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download