I want to find a file with a certain name, but search in direcotories above the current one, instead of below.
I'd like something similar to: (except functional)
$ cd /some/long/path/to/my/dir/
$ find -maxdepth -1 -name 'foo'
/some/long/path/to/foo
/some/foo
Shell scripts or one-liners preferred.
开发者_JS百科In response to the several questions, the difference between the above example and the real find is that the search is proceeding upward from the current directory (and -maxdepth doesn't take a negative argument).
Interesting question, so I try to give a interesting answer :)
find `( CP=${PWD%/*}; while [ -n "$CP" ] ; do echo $CP; CP=${CP%/*}; done; echo / ) ` -mindepth 1 -maxdepth 1 -type f -name 'foo'
A bit of elaborate, the 'while' loop will try in generate list of path which is parent to current directory. The while loop won't generate /, so I add additional 'echo /' to cover that.
Finally, the enclosing "find" command is fairly basic usage.
You could use Parameter Expansion:
path="/some/long/path/to/my/dir"
while [ -n "$var" ]
do
find $path -maxdepth 1 -name 'foo'
path="${var%/*}"
done
This works, but it's not as simple as I hoped.
FILE=foo
DIR=$PWD
while [[ $DIR != '/' ]]; do
if [[ -e $DIR/$FILE ]]; then
echo $DIR/$FILE
else
DIR=`dirname $DIR`
fi
done
If you mean exclude the current dir:
find / -name 'foo' ! -iwholename "$PWD*"
If you mean: direct matches in any dir in the trail, this would work, but my bash-fu is not enough to easily get the list of dirs:
find /some/ /some/long /some/long/path/ /some/long/path/to/ /some/long/path/to/my -maxdepth=1 -name='foo'
So all we need is a method to alter /some/long/path/to/my/dir
to
/some/ /some/long /some/long/path/ /some/long/path/to/ /some/long/path/to/my
精彩评论