xto*_*ofl 15 linux shell path find
我发现我在错误的 stackexchange 站点上问了这个问题。
要查找从某个路径开始的文件,我可以使用find <path> .... 如果我想找到“向上”,即在父目录中,并且它是父目录,并且...,是否有等效的工具?
用例是知道正确的点数(../../x.txt 或 ../../../x.txt?),例如在上游某处包含一些常见 makefile 函数的 makefile 中使用。
像这样的文件夹结构的预期用途:
/
/abc
/abc/dce/efg/ghi
/abc/dce/efg2
$ cd /abc/dce/efg/ghi
$ touch ../../x.txt
$ upfind . -name X*
../../x.txt
$ upfind . -name Y* || echo "not found"
not found
$ touch /abc/dce/efg2/x.txt
$ upfind . -name Y* || echo "not found"
not found
$
Run Code Online (Sandbox Code Playgroud)
简而言之:
cho*_*oba 22
您可以使用这个简单的脚本。它向上遍历目录树并搜索指定的文件。
#!/bin/bash
while [[ $PWD != / ]] ; do
find "$PWD"/ -maxdepth 1 "$@"
cd ..
done
Run Code Online (Sandbox Code Playgroud)
用法:
upfind -name 'x*'
Run Code Online (Sandbox Code Playgroud)
现有答案不充分(详情如下)。
将其放入您的, andupfind中某处命名的脚本中:$PATHchmod +x /the/path/upfind
#!/usr/bin/env bash
DIR=$(readlink -f "$1")
# Alternative: use current working dir; but then also replace ${@:2} with $@ on line 8
# and $1 with $PWD when calling realpath
# DIR=$PWD
while
RESULT=$(find "$DIR"/ -maxdepth 1 "${@:2}")
# echo "Debugging upfind - search in $DIR gives: $RESULT"
[[ -z $RESULT ]] && [[ "$DIR" != "/" ]]
do DIR=$(dirname "$DIR"); done
realpath --relative-to="$1" "$RESULT"
# Alternative: output absolute path
# echo "$RESULT"
Run Code Online (Sandbox Code Playgroud)
您可能考虑的两种替代方案可以在脚本中切换;使用 $PWD 而不是第一个参数意味着我们需要传递 $@ (所有参数)来查找,并通过注释 realpath 行并仅回显 $RESULT 来输出完整路径而不是相对路径。
请注意,do-while 循环的使用来自此 SO 答案。
乔罗巴和马修·沃尔夫的最终条件是错误的;因此他们将无法找到实际上位于文件系统根目录中的文件。他们也都做CD,这不是我希望bash 脚本做的事情。Peter O 的解决方案看起来更好,但只是为我构建的测试用例输出任何内容,并且编写新的 bash 脚本比调试现有脚本更容易。
| 归档时间: |
|
| 查看次数: |
4831 次 |
| 最近记录: |