我通过执行命令 grep error logfile | wc -l
来计算日志文件中的错误数量。
它会输出数字 10。
我想打印出 Error count found in logfile is 10
。
我认为需要通过管道将其传递到 echo 命令,但是如何将 10 追加到 echo 的输出中呢?
我尝试了:
var="$(grep -i error logfile | wc -l)" | echo "Error count found in logfile is $var"
我通过执行命令 grep error logfile | wc -l
来计算日志文件中的错误数量。
它会输出数字 10。
我想打印出 Error count found in logfile is 10
。
我认为需要通过管道将其传递到 echo 命令,但是如何将 10 追加到 echo 的输出中呢?
我尝试了:
var="$(grep -i error logfile | wc -l)" | echo "Error count found in logfile is $var"
var="$(grep -i error * | wc -l)"
echo "Error count found in logfile is $var"
或者你可以使用 bash 命令来定义变量,只用于 echo 命令:
var="$(grep -i error * | wc -l)" ; echo "Error count found in logfile is $var"
echo "Error count found in logfile is $(grep -i error * | wc -l)"
X=42 echo $X
,你不能在下一行使用 $X
。但是如果你执行 X=42; echo $X
,那么你就可以使用了! - zmozsh
中,foo=3; foo=5 echo $foo
输出的是 5 而不是 3?预命令环境赋值在任何 POSIX shell 中都有效,但不会影响命令行中的参数扩展。 - chepnerzshall(1)
来知道哪个是正确的,这不是一个POSIX的问题,只要是Bourne衍生就可以了。 - zmo$(...)
)。echo "Error count found in logfile is $(grep error logfile | wc -l)"
正如Inian的回答中指出的那样,grep
通过其-c
选项直接支持计算匹配次数,因此上述内容可以简化为:
echo "Error count found in logfile is $(grep -c error logfile)"
如果您需要稍后再次引用它,则使用变量存储 grep 的输出是必需的:
注: 变量是指在程序中分配给特定值的命名内存位置。
var=$(grep -c error logfile)
echo "Error count found in logfile is $var"
# ... use $var again as needed
关于您尝试过的方法:echo
只接受命令行参数,不接受标准输入,因此使用管道符(... | echo ...
)是错误的方法。
使用 printf
和 grep
命令,带上 -c
标志可以计算模式出现的次数。
printf "Error count found in logfile is %s\n" "$(grep -chi error logfile)"
GNU grep
中使用的标志
-c, --count
Suppress normal output; instead print a count of matching lines for each input file.
With the -v, --invert-match option (see below), count non-matching lines.
-h, --no-filename
Suppress the prefixing of file names on output. This is the default when there is
only one file (or only standard input) to search.
-i, --ignore-case
Ignore case distinctions in both the PATTERN and the input files.
grep -c
。这里不需要使用 printf
,因为你可以直接将命令替换放入消息中,如 echo "foo $(command)"。 - hek2mglecho "错误数:$(cat * | grep -c error)"
- hek2mgldeclare -i c=0
while read l; do
[[ $l == *error* ]] && ((++c))
done < logfile
echo "Error count found in logfile is $c"`
printf
并直接写成print "blabla", c
。 - fedorquiecho "在日志文件中发现的错误计数为 "$(grep error logfile | wc -l)
echo
命令替换 - 内部的已经足够了。此外,将命令替换嵌入双引号字符串通常更加健壮。 - mklement0使用撇号。
var=`cat x.dat | grep error | wc -l`
echo $var
\`` 不是撇号(单引号),而是技术上的 _重音符号_ (
U+0060),通常称为 _反引号_ (_back tick_)。
`...`是命令替换的 _传统_ 语法,而现代语法是
$(...)`,正如 OP 所使用的那样。 - mklement0