我通过grep error logfile | wc -l
输出10
我想打印Error count found in logfile is 10
我认为需要通过回声来管道它,但我怎样才能将10附加到回声输出?
我试过
var="$(grep -i error logfile | wc -l)" | echo "Error count found in logfile is $var"
答案 0 :(得分:2)
使用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.
答案 1 :(得分:2)
你不应该将var传递给echo,而是按顺序运行它们:
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语句中嵌入命令调用:
echo "Error count found in logfile is $(grep -i error * | wc -l)"
答案 2 :(得分:2)
要简单地将命令中的(stdout)输出嵌入到字符串中,而不需要将该输出存储在变量中,只需使用命令替换({{1} })在双引号字符串($(...)
):
"..."
正如Inian's answer所指出的,echo "Error count found in logfile is $(grep error logfile | wc -l)"
支持通过其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
只接受命令行参数,而不接受stdin输入,因此使用管道(echo
)是错误的方法
答案 3 :(得分:1)
以下是处理此任务的不同方法的更多示例,只是为了帮助您了解bash的功能和选项:
(echo -en "Error count found in logfile is "; grep error logfile | wc -l)
{ printf "Error count found in logfile is " && wc -l < <(grep error logfile); }
printf 'Error count found in logfile is %d\n' $(grep -c error logfile)
awk '/error/{++c} END{printf "Error count found in logfile is %d\n", c}' logfile
var=$(grep -c error logfile); echo "Error count found in logfile is $var"
如果您想要使用“here string”:
cat<<<"Error count found in logfile is $(grep -c error logfile)"
此外,这里只有一个bash内置选项:
declare -i c=0
while read l; do
[[ $l == *error* ]] && ((++c))
done < logfile
echo "Error count found in logfile is $c"`
答案 4 :(得分:-1)
使用撇号。
var=`cat x.dat | grep error | wc -l`
echo $var
答案 5 :(得分:-1)
echo "Error count found in logfile is "$(grep error logfile | wc -l)