查找文件,然后CD到Linux中的该目录 [英] Find file then cd to that directory in Linux
本文介绍了查找文件,然后CD到Linux中的该目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在shell脚本中,我如何查找具有特定名称的文件,然后导航到该目录以对该文件进行进一步的操作?
In a shell script how would I find a file by a particular name and then navigate to that directory to do further operations on it?
从这里,我将文件复制到另一个目录(但是我已经可以将其添加到上下文中了.)
From here I am going to copy the file across to another directory (but I can do that already just adding it in for context.)
推荐答案
您可以使用类似以下内容的
You can use something like:
pax[/home/pax]> cd "$(dirname "$(find / -type f -name ls | head -1)")"
pax[/usr/bin]> _
这将找到第一个 ls
常规文件,然后转到该目录.
This will locate the first ls
regular file then change to that directory.
就每个位的作用而言:
- 查找将从
/
开始并向下搜索,列出所有称为ls
(-name ls
).您还可以添加其他内容到find
中,以进一步限制您获取的文件. - 通过
head -1
的管道将过滤掉除第一个管道以外的所有管道. -
$()
是一种获取命令输出并将其放置在命令行中的另一个命令的方法. -
dirname
可以获取完整的文件规范并为您提供路径位. -
cd
只是更改到该目录.
- The find will start at
/
and search down, listing out all regular files (-type f
) calledls
(-name ls
). There are other things you can add tofind
to further restrict the files you get. - The piping through
head -1
will filter out all but the first. $()
is a way to take the output of a command and put it on the command line for another command.dirname
can take a full file specification and give you the path bit.cd
just changes to that directory.
如果按顺序执行每个位,则可以看到发生的情况:
If you execute each bit in sequence, you can see what happens:
pax[/home/pax]> find / -type f -name ls
/usr/bin/ls
pax[/home/pax]> find / -type f -name ls | head -1
/usr/bin/ls
pax[/home/pax]> dirname "$(find / -type f -name ls | head -1)"
/usr/bin
pax[/home/pax]> cd "$(dirname "$(find / -type f -name ls | head -1)")"
pax[/usr/bin]> _
这篇关于查找文件,然后CD到Linux中的该目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文