Is there a way to find a specific file and then go to the directory containing it at a time?

I am looking for a way to find what I know will be a unique file, and then go to the directory containing this file. Sort of:

find . -name 'Subscription.java' | xargs cd 

Or:

 find . -name 'Subscription.java' -exec cd {} \; 

I know that this will not work because it tries to cd provide the full absolute path that the file contains, and also because xargs cannot execute any shell built-in commands, but you get the point of what I want to achieve.

+4
source share
3 answers
 cd $(find . -name Subscription.java | xargs dirname) 
+7
source

Any attempt at a script a cd should ensure that the command is run in the current shell. Otherwise, if it is running in the child shell, it will not work as you need, since the current working directory of the parent will not be changed.

GNU find has -printf, which you can use to print the directory of any found files. The search result can be passed to cd using Command Substitution.

 cd $(find . -name Subscription.java -printf '%h\n') 

cd (in bash) ignores additional arguments, so if multiple files are found, cd will change to the directory of the first file found.

0
source

Linux / OSX (alternative answer):

 cd `find . -name Subscription.java | xargs dirname` 
0
source

Source: https://habr.com/ru/post/1309043/


All Articles