0

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?

Mathew
  • 235

2 Answers2

1

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).

Kusalananda
  • 333,661
1

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

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

or

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.