I would like to find the directory which keeps a certain file and cd there. e.g.

find * -name hello.txt 

output: Documents/Projects/hello.txt

cd Documents/Projects

How do I pipe these commands? Thanks!

link|improve this question

2  
what would you want to do if find locates more than one copy of hello.txt ? – Iain Sep 6 '11 at 10:44
good question! just goto the location of the first dir which holds hello.txt – OckhamsRazor Sep 6 '11 at 10:46
feedback

3 Answers

up vote 12 down vote accepted

Try

cd $(dirname$(find /path -name hello.txt | head -n 1))

or

cd $(find /path -name hello.txt | head -n 1 | xargs dirname)

You'll need to provide a path to search, * in your above wouldn't work as the shell would expand it.

EDIT and if you have spaces in your filenames

cd $(find /home -name 'he llo.txt' -print0 -quit | xargs -0 dirname)

and if you have spaces in your directory names too

 cd "$(find /path -name 'hello.txt' -print0 -quit | xargs -0 dirname)"
link|improve this answer
dirname, not basename. – quanta Sep 6 '11 at 10:57
thanks Iain, but now i'm getting "usage: dirname path". – OckhamsRazor Sep 6 '11 at 11:21
adding quotations solves it. however, your solution does not work for directories whose names have spaces in them. do you know how that could be done? thanks! – OckhamsRazor Sep 6 '11 at 11:28
Put quotes around the subshell "$( find ...)" – Iain Sep 6 '11 at 11:39
awesome, well done! – OckhamsRazor Sep 6 '11 at 11:50
feedback

Instead of finding all and head -1, just use -quit option to make find command stop after the first hello.txt file was found:

$ cd $(dirname $(find /path -name hello.txt -print -quit))
link|improve this answer
oooh - -quit I like that – Iain Sep 6 '11 at 11:11
feedback

solution 1 find * -name hello.txt | xargs dirname

solution 2 find . -type d -print

link|improve this answer
Your first solution doesn't change into the directory, just displays it. The second solution wouldn't work at all, as you are only searching for directories, not files. – SvenW Sep 6 '11 at 11:04
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.