使用 bash 在目录树中按名称查找文件

问题描述 投票:0回答:4

使用

bash
,如何从
pwd
的目录树中查找具有特定名称的文件?

更清楚一点。我想找到位于工作目录根目录中的文件,但我不知道根目录在哪里,并且我的

pwd
可能位于根目录下方的任何位置。

bash find
4个回答
19
投票

查找

file.txt
直至根目录

x=`pwd`
while [ "$x" != "/" ] ; do
    x=`dirname "$x"`
    find "$x" -maxdepth 1 -name file.txt
done

10
投票
local DIR=$(pwd)
while [ ! -z "$DIR" ] && [ ! -f "$DIR/myFile.txt" ]; do
    DIR="${DIR%\/*}"
done
echo $DIR/myFile.txt

4
投票

我在 ~/.bashrc 中定义了以下函数:

dnif () { 
    # Recursively list a file from PWD up the directory tree to root
    [[ -n $1 ]] || { echo "dnif [ls-opts] name"; return 1; }
    local THERE=$PWD RC=2
    while [[ $THERE != / ]]
        do [[ -e $THERE/${2:-$1} ]] && { ls ${2:+$1} $THERE/${2:-$1}; RC=0; }
            THERE=$(dirname $THERE)
        done
    [[ -e $THERE/${2:-$1} ]] && { ls ${2:+$1} /${2:-$1}; RC=0; }
    return $RC
}

它将在每个目录中从当前目录向上搜索到根目录中作为参数提供的名称,如果找到,则用“ls”和您提供的可选 ls 选项列出它。输出示例:

me@host:~/dev/example
$ dnif; echo $?
dnif [ls-opts] name
1
me@host:~/dev/example
$ dnif -alp nonesuch; echo $?
2
me@host:~/dev/example
$ dnif -alp .bashrc; echo $?
-rw-r--r-- 1 me mine 3486 Apr  3  2012 /home/me/.bashrc
0
me@host:~/dev/example
$ dnif -d .
/home/me/dev/example/.
/home/me/dev/.
/home/me/.
/home/.
/.

请注意:

  • “dnif”是向后“查找”。
  • 该函数是一个有限循环(非递归),不创建子 shell,并尽可能使用 Bash 内置函数来提高速度。
  • 列出了每个升序目录级别的所有点击。
  • ls -opt 是可选的,但必须位于所需的搜索参数之前。
  • 搜索参数可以是文件或目录。
  • 如果搜索参数是目录,请包含 ls -opt '-d' 以将结果限制为目录名称而不是内容。
  • 函数返回退出代码
    • 0 如果至少有一次命中,
    • 1 如果没有提供参数来寻求帮助,并且
    • 2 如果什么也没找到。

0
投票

与@kev的答案类似,但作为一个函数尝试向上定位(子)文件到根文件夹(首选字符串操作而不是像dirname tr等函数调用)

# @usage: `dir_containing [--stop=<dir>] <sub-path-to-find>`
# @params: 1) (sub-)filename to find, 2) starting-dir (defaults to PWD)
# @options: --stop=<dir> directory where to stop searching (default: <root>)
# @return: directory-path (where the (sub-)filename was found),
#          otherwise empty string (along with a non-zero errorcode)
# @throws: #400 if called without parameters, #404 if not found
# @alias:  upfind, find_upward
dir_containing() {
    local stop=""; [[ "$1" = --stop=* ]] && { stop="$( realpath "${1/--stop=/}" )"; shift; }
    [ "$1" ] || return 400
    local d="$( realpath "${2:-"$PWD"}" )"
    while [ "$d" ] && [ "$d" != "$stop" ] && [ ! -e "$d/$1" ]; do d="${d%/*}"; done
    [ -e "$d/$1" ] && echo "${d:-/}" || return 404
}
© www.soinside.com 2019 - 2024. All rights reserved.