![](/img/trans.png)
[英]cd && ls | grep: How to execute a command in the current shell and pass the output
[英]How to cd into grep output?
我有一个Shell脚本,它基本上会搜索某个位置内的所有文件夹,并且我使用grep来查找要定位的确切文件夹。
for dir in /root/*; do
grep "Apples" "${dir}"/*.* || continue
尽管grep成功找到了目标目录,但我仍在如何移动要移动到目标目录中的文件夹。 我当时的想法是cd到grep输出,但这就是我遇到的问题。 尝试了一些Google结果,但对我的案子没有任何帮助。
grep输出示例:二进制文件/root/ant/containers/secret/Documents/2FD412E0/file.extension matches
我想光盘进入2FD412E0
并在该目录中移动两个文件夹。
dirname是实现此目的的关键:
cd $(dirname $(grep "...." ...))
将允许您输入目录。
就像人们提到的那样, dirname
是从路径中删除文件名的正确工具。
我将使用find
执行此类任务:
while read -r file
do
target_dir=`dirname $file`
# do something with "$target_dir"
done < <(find /root/ -type f \
-exec grep "Apples" --files-with-matches {} \;)
考虑使用find
的-maxdepth
选项。 有关find
请参见手册页。
好吧,实际上有一个更简单的解决方案:)我只想编写bash脚本。 您可能只是使用单个find
命令,如下所示:
find /root/ -type f -exec grep Apples {} ';' -exec ls -l {} ';'
注意第二个-exec
。 如果先前的-exec
命令以状态0
(成功)退出,它将被执行。 从手册页:
-exec command ;
执行命令; 如果返回0状态,则为true。 后面的所有要查找的参数都将用作命令的参数,直到参数由;
组成;
遇到。 字符串{}
会被当前文件名替换,该文件名会在命令参数中出现的所有位置处进行处理,而不仅仅是在单独的参数中(例如在某些版本的find中)。
用您的东西替换ls -l
命令。
如果要在-exec
命令中执行dirname
,则可以执行以下技巧:
find /root/ -type f -exec grep -q Apples {} ';' \
-exec sh -c 'cd `dirname $0`; pwd' {} ';'
用您的东西替换pwd
。
什么时候find
在您写的注释中, find
在您的系统上不可用。 以下解决方案无法find
:
grep -R --files-with-matches Apples "${dir}" | while read -r file
do
target_dir=`dirname $file`
# do something with "$target_dir"
echo $target_dir
done
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.