3

我想运行一个find命令,然后计算输出的行数并给出结果的输出。我的直接方法是这样的:

output=$(find ...)
lines=$(echo "$output" | wc -l)
echo "$output"

但不幸的是,使用echo管道将其wc添加到换行符中,因此即使find没有找到任何内容(零行输出),wc也会发出1(对于echo附加的换行符。

我将其更改echo为 a以防止将换行符附加到输出中,但类似printf的单行输出也没有换行符,因此给出了 out 。findvar/wc0

问题在于捕获输出 ( $(...))。它去除了在我的情况下相关的尾随换行符。

可以以某种方式防止这种情况吗?

我的原始任务有完全不同的方法吗?

4

3 回答 3

5

一个简单的解决方法是检查字符串是否为空:

[ -z "$output" ] && count=0 || count=$(wc -l <<< "$output")

现在count将是0如果find没有产生任何输出,否则它将包含输出中的行数。

于 2014-04-25T13:59:21.053 回答
3

如果您的文件名包含空格或新行,则在将 find 的输出存储在变量中后计算新行总是会出现问题。

我建议像这样使用 find (计算所有*.txt文件并打印它们)

output=
c=0

while read -d ''; do 
    ((c++))
    output+="$REPLY"$'\n'
done < <(find . -name "*.txt" -print0)

echo "c=$c"
echo "output=$output"

PS:这也将处理文件名中的新行/空格。

于 2014-04-25T14:02:15.693 回答
2

我现在通过在输出中附加一条假线来使用一种解决方法;这样我就可以依靠一行总是存在的事实,这样空行很容易与单行区分开来:

r=$(find var/ -name var -printf "%p\n"; echo '==')
# appending additional line to be able to distinguish 0 from 1 found file
case "$(echo "$r" | wc -l)" in
  1)  # means 0 found files
    ...
  2)  # means 1 found file
    ...
  *)  # means more found files
    ...
esac
于 2014-04-25T14:34:45.563 回答