要查找从某个path开始的文件,我可以使用find <path> ... 如果我想find'向上',即在父目录,它的父母,…,是否有一个等效的工具?
这样的文件夹结构的用途:
/ /abc /abc/dce/efg/ghi $ cd /abc/dce/efg/ghi $ touch ../../x.txt $ upfind . -name X* ../../x.txt $ upfind . -name Y* $
x="$(pwd)"; while [ "$x" != "/" ]; do if [ -e "${x}/X.txt" ]; then echo $x; fi; x="$(dirname "$x")"; done
为什么不只是做一个向下recursionfind / ? 他们都将search整个文件空间。 或者,你是否要求有一个旅行起来, 但不会在search中find的目录中旅行 ?
如果你想要文件的父目录,你可以使用find和-printf %h参数
find /abc -name X.txt -printf "%h\n" /abc/dce
文件名称的引导目录(除最后一个元素外)。 如果文件名不包含斜杠(因为它在当前目录中),%h说明符将扩展为“。”。
基于@Womble的想法 ,我写了一个小窍门:
#!/bin/bash # # rfind: finds a file in one of the parent directories needle=$1 current_dir=$(pwd) path= while [ "$current_dir" != "$(dirname $current_dir)" ]; do if [ -e "${current_dir}/$needle" ]; then echo $path$needle exit 0 else path=../$path current_dir="$(dirname "$current_dir")" fi done if [ ! "$current_dir" != "$(dirname $current_dir)" ]; then echo "rfind: file $needle not found" >&2 exit 1 fi
并在我自己的〜/ bin目录中命名为'rfind'。 它的诀窍是:
/tmp $ mkdir -px/y/z /tmp $ cd x/y/z/ /tmp/x/y/z $ rfind a.txt || echo "not found." rfind: file a.txt not found not found. /tmp/x/y/z $ touch ../../a.txt /tmp/x/y/z $ rfind a.txt || echo "not found." ../../a.txt /tmp/x/y/z $ /tmp/x/y/z $ cd .. /tmp/x/y $ mkdir z2 /tmp/x/y $ cd z /tmp/x/y/z $ touch ../z2/a.txt /tmp/x/y/z $ rfind a.txt || echo "not found." ../../a.txt /tmp/x/y/z $ rm ../../a.txt /tmp/x/y/z $ rfind a.txt || echo "not found." rfind: file a.txt not found not found.