In the Mac terminal, how do I "find" a file and then quickly cd to the parent directory?

3

I want to open terminal, find a file or folder, and quickly navigate to that folder or the parent directory of the file.

I can quickly get the path using

find ~ -name 'filename.txt' 

but I can't figure out how to copy that path result into the "cd" command

Is there a way to basically say "cd [path from find command]" or "open [path from find command]"

I'm just using the default terminal in OSX Mountain Lion

Jeff Widman

Posted 2013-06-18T05:34:10.980

Reputation: 133

Answers

3

How about:

cd $(find -name "filename.txt" -type f -exec dirname {} \; | sed 1q)

jaypal singh

Posted 2013-06-18T05:34:10.980

Reputation: 2 134

it's a workable solution, but not clean like I was hoping... oh well, I guess there isn't a simple clean solution like I was hoping – Jeff Widman – 2013-07-18T22:58:02.827

0

Like this:

$ cd `find ~ -name filename.txt -exec dirname {} \;`

Paul R

Posted 2013-06-18T05:34:10.980

Reputation: 4 717

Stalker!!!! :-) – jaypal singh – 2013-06-18T05:48:11.483

@JS: heh - well someone's got to answer all these find questions... ;-) – Paul R – 2013-06-18T05:58:58.523

1Yes Sir!! Now we just got to wait for mods to move it to SuperUser. Sigh! – jaypal singh – 2013-06-18T06:01:14.373

I just tried this and got a "No such file or directory error".$ cdfind ~ -name filename.txt -exec dirname {} ;`` results in an error, but the find command by itself works perfectly:$ find ~ -name 'filename.txt' works perfectly.

(I also can't figure out how to use markdown to delineate the code above because the code contains backticks so markdown stops the code formatting part early) – Jeff Widman – 2013-07-02T18:22:02.637

What happens if you just run $ find ~ -name filename.txt -exec dirname {} \; ? – Paul R – 2013-07-02T20:30:28.557

0

If have added this to ~/.inputrc to make \eo rerun the previous command and insert its output:

"\eo": "$(!!)\e\C-e"

Or if you use bash 4.0 or later, you can enable globstar and press \eg to expand patterns like this:

cd **/filename.txt

You can delete the filename part in both cases with option-delete.

Lri

Posted 2013-06-18T05:34:10.980

Reputation: 34 501