im trying to find my .csv files then cd into their directory:

find Documents/notes -type f -name "*.csv" | head -1 | xsel -b

this copies the first file dir into my clipboard and i'd like to then run:

cd $(xsel -b) 

but ofcourse I can't because it's including the filename which isn't a directory.

Is there anyway to omit the filename? is there a better way to do this?


2 Answers 2


Using the bash shell, enable the ** pattern (matches like *, but also reaches past / in pathnames), then expand the pattern Documents/notes/**/*.csv, and then cd to the directory of the first match:

shopt -s globstar
set -- Documents/notes/**/*.csv
cd "$(dirname "$1")"    # or: cd "${1%/*}"

With zsh, which already has the ** pattern enabled by default, this can be shortened into

cd Documents/notes/**/*.csv([1]:h)

The glob qualifier ([1]:h) returns the directory name ("h" as in "head of the path") of the first match of the given pattern. Change this qualifier to (.[1]:h) to make the pattern match only regular files (or symbolic links to such files).

  • how would i enable the ** pattern?
    – Mathew
    Sep 17, 2023 at 20:39
  • @Mathew As I mentioned in the text, the bash shell would require shopt -s globstar, whereas it would be enabled by default in the zsh shell. If you are using some other shell, you should mention this in your question.
    – Kusalananda
    Sep 17, 2023 at 20:42
  • okay understood thanks!
    – Mathew
    Sep 17, 2023 at 20:44

Yes, using only find (need -quit support):

dir=$(find . -name '*.csv' -print -quit)
cd "$(dirname "$dir")"


cd "$(dirname "$(find . -name '*.csv' -print -quit)")"

it breaks on the first match.

-quit :

Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, find /tmp/foo /tmp/bar -print -quit will print only /tmp/foo. One common use of -quit is to stop searching the file system once we have found what we want.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .