6

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!

  • 2
    what would you want to do if find locates more than one copy of hello.txt ? – user9517 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
13

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)"
  • 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 ...)" – user9517 Sep 6 '11 at 11:39
  • awesome, well done! – OckhamsRazor Sep 6 '11 at 11:50
8

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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