簡體   English   中英

如何通過管道 wc -l 輸出到 echo 輸出

[英]how to pipe wc -l output to echo output

我通過執行grep error logfile | wc -l計算日志文件中的grep error logfile | wc -l 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 輸入 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)"

簡單地嵌入(標准輸出)從一個字符串命令的輸出,而不需要還可以存儲在一個變量,它的輸出,只需使用一個命令替換( $(...)在雙引號內的字符串( "..."

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 ... )是錯誤的方法。

使用帶有-c標志的printfgrep進行模式計數。

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.

以下是處理此任務的不同方法的更多示例,只是為了幫助您了解 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"`

使用撇號。

var=`cat x.dat | grep error | wc -l`
echo $var

echo "Error count found in logfile is "$(grep error logfile | wc -l)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM