I want to find a file and then enter the directory containing it. I tried
find /media/storage -name "Fedora" | xargs cd but of course, I the
is not a directory error.
How do I enter its parent directory with a one line command?
At least if you have GNU
find, you can use
-printf '%h' to get the directory
%h Leading directories of file's name (all but the last ele‐ ment). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to ".".
So you could probably do
cd "$(find /media/storage -name "Fedora" -printf '%h' -quit)"
-quit should prevent multiple arguments to
cd in the case more than one file matches.
Similar to steeldriver's solution but using
-execdir (if your
find supports it, like GNU's or FreeBSD's
find) in combination with
cd "$(find /media/storage -name "Fedora" -execdir pwd \; -quit)"
-quit is optional in case only there is only a single result and crawling the whole directory there is of no issue. On NetBSD it's
-exit and on OpenBSD it does not exist.
You can make find run a new shell in the directory it finds.
exec find /media/storage -name "Fedora" -execdir "$SHELL" \;
, after which the current directory will be the one which has a file named Fedora in it. ;)
Obviously this only does something resembling what you want if you are typing commands interactively.
cd into the first (in alphabetical order) directory that contains a file called
**: any level of directories (hidden dirs are omitted by default, use the
Dglob qualifier to include them)
: only the first
:h: head modifier: take the dirname.
cd "$(find ...)", it also works if the directory name ends in a newline character. Another advantage is that you'd get a no match error message when there's no matching directory (while in most shells
cd "" would do nothing silently).
A drawback is that it would crawl the whole of
/media/storage before returning.