【问题标题】:How to find errors in a file using for loop如何使用for循环查找文件中的错误
【发布时间】:2021-11-26 15:47:58
【问题描述】:

如何使用for 循环从文件中找到错误(Error1、Error2、Error 3)。

一个文件包含来自 4 不同机器的三种类型的错误 (strings)。任何机器都可能有任意数量的错误。 whiptail 用于在发现错误时创建pop-up window

#!/bin/sh

 
if grep -R "Error1 in Machine 1" /home/new/Report.txt
then
echo "Error1 found in Machine 1"
whiptail --title "Report Error" --msgbox "Error 1 in Machine 1" 8 78
else
echo "No Error found"
fi


if grep -R "Error2 in Machine 1" /home/new/Report.txt
then
echo "Error2 found in Machine 1"
whiptail --title "Report Error" --msgbox "Error 2 in Machine 1" 8 78
else
echo "No Error found"
fi


if grep -R "Error2 in Machine 2" /home/new/Report.txt
then
echo "Error2 found in Machine 2"
whiptail --title "Report Error" --msgbox "Error 2 in Machine 2" 8 78
else
echo "No Error found"
fi


if grep -R "Error3 in Machine 3" /home/new/Report.txt
then
echo "Error3 found in Machine 3"
whiptail --title "Report Error" --msgbox "Error 3 in Machine 3" 8 78
else
echo "No Error found"
fi

【问题讨论】:

  • grep 中的-R 选项的用途是什么?

标签: linux bash shell script


【解决方案1】:
#!/bin/bash

grep 'Error[1-3] in Machine [1-4]' /home/new/Report.txt |
while IFS= read -r errmsg
do
        whiptail --title "Report Error" --msgbox "$errmsg" 8 78
done

脚本没有显示“未找到错误”消息(没有消息就是好消息),否则应该可以工作。

【讨论】:

  • 这会弹出比需要更多的错误信息
【解决方案2】:

如果你有 3 个错误和 4 台机器,你可以使用嵌套循环来处理所有 12 种组合:

for ((e = 1; e <= 3; e++)); do
  for ((m = 1; m <= 4; m++)); do
    message="Error$e in Machine $m"
    if grep -qF "$message" /home/new/Report.txt; then
      echo "$message"
      whiptail --title "Report Error" --msgbox "$message" 8 78
    else
      echo "No Error found"
    fi
  done
done

grep 选项q(安静)和F 用于不打印任何内容并将模式解释为固定字符串,而不是正则表达式。

【讨论】:

  • 雷诺帕卡莱特 谢谢您的回复。由于在 for 循环中使用了whiptail,因此只要在文件中发现错误,代码就会弹出一个窗口。如何在 for 循环之外使用whiptail,以便它显示文件中所有错误的列表。例如,如果我在 m1 中得到 e1,在 m3 中得到 e2,在 m3 中得到 e3。如何在一个弹出窗口中显示所有这 3 个错误。
  • 这与您的问题不同。 SO 也适用于可能遇到类似问题的其他人,因此问题和答案必须完美同步。请首先编辑您的问题并解释您只需要一个弹出窗口(而不是您当前问题中的多个),并清楚地解释当只有一个错误以及有多个错误时消息应该是什么样子。不要在 cmets 中解释这一点,只在你的问题中。
  • 我现在编辑了我的问题。请您现在检查一下吗
  • 对不起,但你的问题(至少我能看到的版本)仍然没有说明你只想打一次whiptail,也没有说明你想在弹出窗口中看到什么消息出现多个错误时的窗口。
  • Renaud Pacalet,我创建了一个包含一些细节的新问题
【解决方案3】:

传递grep(1) 一次并保存输出,然后执行其余的操作。

#!/usr/bin/env bash

mapfile -t error_message < <(grep 'Error[[:digit:]] in Machine [[:digit:]]' /home/new/Report.txt)

((${#error_message[*]})) || { printf >&2 'No error message found\n'; exit; }

for message in "${error_message[@]}"; do
  printf '%s\n' "$message"
  whiptail --title "Report Error" --msgbox "$message" 8 78
done

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多