Hrv*_*e T 12 shell find xargs cd-command
我想找到一个文件,然后进入包含它的目录。我试过了,find /media/storage -name "Fedora" | xargs cd
但当然,我的is not a directory
错误。
如何使用一行命令进入其父目录?
ste*_*ver 15
至少如果你有 GNU find
,你可以使用-printf '%h'
来获取目录
%h Leading directories of file's name (all but the last ele?
ment). If the file name contains no slashes (since it is
in the current directory) the %h specifier expands to
".".
Run Code Online (Sandbox Code Playgroud)
所以你可能会这样做
cd "$(find /media/storage -name "Fedora" -printf '%h' -quit)"
Run Code Online (Sandbox Code Playgroud)
在-quit
多个cd
文件匹配的情况下,应该防止多个参数。
类似于steeldriver 的解决方案,但结合使用-execdir
(如果您find
支持它,如 GNU 或 FreeBSD 的find
)pwd
:
cd "$(find /media/storage -name "Fedora" -execdir pwd \; -quit)"
Run Code Online (Sandbox Code Playgroud)
-quit
如果只有一个结果并且抓取整个目录没有问题,则是可选的。在 NetBSD 上它是,-exit
而在 OpenBSD 上它不存在。
小智 5
你可以让 find 在它找到的目录中运行一个新的 shell。
exec find /media/storage -name "Fedora" -execdir "$SHELL" \;
Run Code Online (Sandbox Code Playgroud)
, 之后当前目录将是其中包含名为 Fedora 的文件的目录。;)
显然,如果您以交互方式键入命令,这只会执行类似于您想要的操作。