Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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!

share|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
add comment

2 Answers

up vote 13 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)"
share|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
add comment

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))
share|improve this answer
    
oooh - -quit I like that –  Iain Sep 6 '11 at 11:11
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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