使用BASH,如何在变量集上使用wc -l来设置find命令的输出?

时间:2016-01-28 18:14:31

标签: bash

警告:我是个菜鸟。 无论如何,如果我有var foo=$(find / \( -name "Test.txt" \)),并且知道使用相同的find命令并将输出汇总到wc -l会给出正确的结果计数;如何仅使用foo(而非另一个查找)计算结果?bash

2 个答案:

答案 0 :(得分:4)

您可以使用“here string”:

wc -l <<<"$foo"

(见§3.6.6 "Here Documents" and §3.6.7 "Here Strings" in the Bash Reference Manual。)

答案 1 :(得分:1)

在Bash中,您可以使用here字符串:

wc -l <<<"$foo"

传统上,您必须单独管道它:

printf "%s\n" "$foo" | wc -l

但是,如果可以,我建议避免将大结果存储在变量中。如果目标(根据您的某些评论中的建议)是删除您找到的文件并报告已删除的文件数量,那么我会执行类似

的操作
find / -name "*.lproj" -not -name "en*" -not -name "En*" \
  -not -name "Base*" -printf '.' -delete |
wc -c |
sed 's/.*/Found and deleted & files./'

(如果您的find不支持-printf-delete - 这是GNU find扩展程序 - 您需要-exec一些外部工具。那么也许你想要将整个代码片段重构为在一个简单的shell脚本中运行的东西。)