【问题标题】:Bash Script Output to console and fileBash 脚本输出到控制台和文件
【发布时间】:2017-08-08 10:07:04
【问题描述】:

我需要一个小脚本来搜索日志文件中的字符串并计算行数。因为这可能需要一段时间,所以我还希望在控制台中显示“grep”的输出。我的想法是这样的:

grep -irl "System out of memory" | tee /tmp/checkoom.tmp
COUNT=(cat /tmp/checkoom.tmp |wc -l)
echo $COUNT logs found.

但它不起作用。我没有得到任何输出,tmp 文件已创建但似乎为空。

【问题讨论】:

    标签: linux bash grep tee


    【解决方案1】:

    您忘记提供搜索的起始目录:

    grep -irl "System out of memory" <somewhere> | tee /tmp/checkoom.tmp
    

    【讨论】:

      【解决方案2】:

      脚本有两个错误:

      • grep 路径
      • $() 用于执行命令。这必须在分配变量 COUNT 时添加

      更新脚本:

      #!/bin/bash
      grep -irl "System out of memory" <path to search> | tee /tmp/checkoom.tmp
      COUNT=$(cat /tmp/checkoom.tmp | wc -l)
      echo "$COUNT" logs found.
      

      您也可以在 grep 中使用 -F 选项。 -F 代表固定字符串

      【讨论】:

      • 奇怪,它仍然不起作用。如果我使用不带 | 的 grep 命令tee,一切都很好......
      • 这应该在正常情况下工作。尝试使用“查找”。 Butgrep 是正确的选择 :) 尝试使用命令 >> #find -type f -exec grep -irl "System out of memory" {} \; > /tmp/checkoom.tmp
      【解决方案3】:

      这是从 /var/log/messages 获取 USB 记录的唯一方法:

      echo "$(grep -i '/lib/udev/usb' /var/log/messages > ~/yourFile ; cat ~/yourFile | wc -l ) logs found"
      

      希望对你有用

      【讨论】:

        最近更新 更多