【问题标题】:Add a total to output of bash script将总计添加到 bash 脚本的输出中
【发布时间】:2023-03-03 22:07:01
【问题描述】:

我正在运行一个 bash 脚本,它查看错误日志并生成在 Mac 终端中打印的报告。

目前,输出如下所示:

This error report is derived from Command Logs from ________ to __________.

IP addresses:

109.xx.xxx.xxx

Error Codes List: 

(code 12)
(code 30)

Common Errors - Count: 

Code 2: 
Code 10: 
Code 11: 
Code 12: 237
Code 14: 
Code 20: 
Code 23: 
Code 30: 5
Code 35: 
Code 37: 
Code 52: 
/usr/local/bin/backerr: line 45: `$skipping': not a valid identifier
Total: 242

Total Files Transferred: 
3558

Count complete.

The following are details for each error:   
// all of the 242 above-referenced lines //

Skipped files: 
// lists all of the lines that have the word 'skipping\ ' //

如您所见,我没有正确的标识符:

    /usr/local/bin/backerr: line 45: `$skipping': not a valid identifier

这是我必须检测其中包含“skipping\”的行的代码,计算总数,并在上面的代码 XX: total 下打印总数。另外,我希望将“skipping\”总数添加到“Total:242”中。

  count=()
  total=0

  while read skipping; do
        (( count[$skipping]++, total++ ))      
  done < <(grep 'skipping\ ' $input_variable)

  for $skipping in $input_variable; do
    echo "Skipped: ${count[$skipping]}"
  done

“常见错误 - 计数:”部分的预期输出应如下所示:

    Common Errors - Count: 

    Code 2: 
    Code 10: 
    Code 11: 
    Code 12: 237
    Code 14: 
    Code 20: 
    Code 23: 
    Code 30: 5
    Code 35: 
    Code 37: 
    Code 52: 
    Skipped: 107 (I made up this number for this question)
    Total: 349

我被困在这里。请帮忙。

作为一种解决方法,而不是使用下面的代码:

      while read skipping; do
            (( count[$skipping]++, total++ ))      
      done < <(grep 'skipping\ ' $input_variable)

      for $skipping in $input_variable; do
        echo "Skipped: ${count[$skipping]}"
      done

我将其替换为:

  echo "Total Skipped Files: " ; egrep -c 'skipping' $input_variable ;

但是,这并没有真正产生我最初设想的理想结果。

【问题讨论】:

  • 为什么是&lt; &lt; 而不是&lt;
  • @SMA: Process substitution:将命令的输出视为文件。
  • 在所有代码总数下方(代码 2:代码 10:代码 11:代码 12:237 代码 14:代码 20:代码 23:代码 30:5 代码 35:代码 37:代码 52: )' 我想要一行写着 'Skipped: 'n'' 其中 'n' 是总数。然后,我想将跳过的总计添加到底部的总计中。你明白吗?
  • 我刚刚用所需的输出更新了问题。谢谢。
  • 嗯,但是您是如何从上面的输入中获得 107349 数字的?

标签: bash function for-loop while-loop


【解决方案1】:

您的 for 循环不应为索引变量使用美元符号:

for skipping in $input_variable; do
   ^^^ 

【讨论】:

  • 我这样做了,但我得到了`/usr/local/bin/script: line 44: filename: syntax error: invalid algorithm operator (error token is "@filename"'
  • @technerdius 您的脚本中的“文件名”在哪里?
  • 文件名是 $input_variable
猜你喜欢
  • 2023-03-16
  • 2022-01-20
  • 2020-03-29
  • 1970-01-01
  • 2013-12-02
  • 2021-08-05
  • 2020-03-22
  • 2016-04-28
  • 1970-01-01
相关资源
最近更新 更多