我想找到保存某个文件和 cd 的目录。例如
find * -name hello.txt
Run Code Online (Sandbox Code Playgroud)
输出:文档/项目/hello.txt
cd Documents/Projects
Run Code Online (Sandbox Code Playgroud)
我如何通过管道传输这些命令?谢谢!
use*_*517 13
尝试
cd $(dirname$(find /path -name hello.txt | head -n 1))
Run Code Online (Sandbox Code Playgroud)
或者
cd $(find /path -name hello.txt | head -n 1 | xargs dirname)
Run Code Online (Sandbox Code Playgroud)
你需要提供一个path来搜索,*在你的上面不起作用,因为外壳会扩展它。
编辑,如果您的文件名中有空格
cd $(find /home -name 'he llo.txt' -print0 -quit | xargs -0 dirname)
Run Code Online (Sandbox Code Playgroud)
并且如果您的目录名称中也有空格
cd "$(find /path -name 'hello.txt' -print0 -quit | xargs -0 dirname)"
Run Code Online (Sandbox Code Playgroud)
而不是查找所有 and head -1,只需使用-quit选项使find命令在hello.txt找到第一个文件后停止:
$ cd $(dirname $(find /path -name hello.txt -print -quit))
Run Code Online (Sandbox Code Playgroud)