Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在bash中将find命令与管道一起使用?_Bash - Fatal编程技术网

如何在bash中将find命令与管道一起使用?

如何在bash中将find命令与管道一起使用?,bash,Bash,目录结构如下所示 home --dir1_foo ----subdirectory..... --dir2_foo --dir3_foo --dir4_bar --dir5_bar 我试图先使用'find'命令来获取包含特定字符串的目录(在本例中为'foo'),然后再次使用'find'命令来检索一些与条件匹配的目录 所以,我首先尝试了 #!/bin/bash for dir in `find ./ -type d -name "*foo*" `; do for subdir in `f

目录结构如下所示

home
--dir1_foo
----subdirectory.....
--dir2_foo
--dir3_foo
--dir4_bar
--dir5_bar
我试图先使用'find'命令来获取包含特定字符串的目录(在本例中为'foo'),然后再次使用'find'命令来检索一些与条件匹配的目录

所以,我首先尝试了

#!/bin/bash
for dir in `find ./ -type d -name "*foo*" `;
do
    for subdir in `find $dir -mindepth 2 -type d `;
    do
       [Do some jobs]
    done
done
,这个脚本很好用

然后我想,只使用一个循环和下面这样的管道也可以,但这不起作用

#!/bin/bash
for dir in `find ./ -type d -name "*foo*" | find -mindepth 2 -type d `;
do
   [Do some jobs]
done
实际上,这个脚本的工作原理与

for dir in `find -mindepth 2 -type d`;
do
   [Do some jobs]
done
,这意味着第一个find命令将被忽略


问题出在哪里?

您的脚本所做的不是一个好的实践,并且有很多潜在的陷阱。看看,了解原因

您可以使用
xargs
-0
读取空分隔文件,并使用另一个
find
命令,而无需使用for循环

find ./ -type d -name "*foo*" -print0 | xargs -0 -I{.} find {.} -mindepth 2 -type d 
xargs
-I
后面的字符串充当从上一个管道接收的输入的占位符,并将其传递给下一个命令。
-print0
选项是特定于GNU的,这是处理包含空格或任何其他shell元字符的文件名/目录名的安全选项

因此,在执行上述命令后,如果您有兴趣对第二个命令的输出执行某些操作,请使用
while
命令执行进程替换语法

while IFS= read -r -d '' f; do
    echo "$f"
    # Your other actions can be done on "$f" here
done < <(find ./ -type d -name "*foo*" -print0 | xargs -0 -I{.} find {.} -mindepth 2 -type d -print0)
而IFS=read-r-d''f;做
回音“$f”
#您可以在此处的“$f”上执行其他操作

如果可以的话,尽量避免。使用
-exec
primary运行包含命令的脚本,或者尝试改用路径名扩展。在本例中,看起来您可以在*foo*/*/*foo*/*中对dir使用
;执行
以获取您的
查找命令所需的相同目录,这样做的好处是可以使用任何合法的目录名。