如何使用 for 循环查找文件中的错误

How to find errors in a file using for loop

如何使用 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

如果您有 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 用于不打印任何内容并将模式解释为固定字符串,而不是正则表达式。

通过 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
#!/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

脚本没有显示“未发现错误”消息(没有消息就是好消息),但除此之外应该可以。