如何根据条件循环遍历文件

时间:2017-11-17 13:32:22

标签: bash shell unix

我有一个包含以下内容的文件。文件名是" myXLog.txt":

IAAS Session factory creation started

X

Y

z

Communications link failure

我想要的是读取文件,如果字符串" IAAS会话工厂创建开始"找到然后继续阅读,如果另一个字符串"通信链接失败"找到然后返回一条消息。我的代码只获得第一行,而不是更进一步。请帮助我在互联网上检查了很多帮助,但由于我不熟悉shell脚本(非常新),所以无法管理.`

#!/bin/bash
filename="myXLog.txt"    
while read line
do

if [[ $line == "IAAS Session factory creation started" ]] ; then
       a="YES"
       echo $a
       if a="YES"; then #HERE I WANT TO CONTINUE READING BUT NOT SURE HOW
       if [[ $line == "Communications link failure" ]] ; then
            echo "ERROR"

       else echo "ALL IS WELL"      $line
       fi
       fi
else echo "BYE"
    #fi
fi
done < $filename

仅打印

YES

一切都很好IAAS会议工厂创建开始

BYE

BYE

BYE

BYE

2 个答案:

答案 0 :(得分:1)

我认为如果你停止筑巢你的条件,这将有效。你基本上想要测试&#34;如果我已经看过&#39;开始&#39;线和当前线是&#39;结束&#39;行,打印一些东西和break out of the loop&#34;。目前,代码只检查错误消息,当它在同一行时,就像它找到&#34; start&#34;消息,永远不会是真的,因为该行可以是开始或结束消息,但不能同时是两者。相反,你想跟踪我已经看到了开始消息&#34;在循环的变量外部中(好吧,它可能在里面,因为Bash默认为全局变量,但是将它放在外面使事情更容易理解),当你看到&#时设置该变量34;开始&#34;行,然后在每个后续行,检查错误&#34;找到开始&#34;变量

我认为以下代码可能会成功。有很多较短的方法可以做到这一点,但这个是最容易理解的(对我而言):

#!/bin/bash
filename="myXLog.txt"
found=""
while read line; do
    if [[ $line == "IAAS Session factory creation started" ]]; then
        echo "START: $line"
        found="start"
    # This tests: "Have we found the start line, and is the line the error message?"
    elif [[ $found == "start" && $line == "Communications link failure" ]]; then
        found="error"
        echo "ERROR: $line"
        break
    elif [[ $found == "start" ]]; then
        echo "ALL IS WELL: $line"
    fi
    # Implicit else: if we have not yet seen the 'started' line, do nothing.
done < $filename

在循环运行之后,您可以检查$found变量的值,看它是否到达文件的末尾而没有看到错误,例如:

# Check if $found is empty.
if [[ -z $found ]]; then
    echo "Never found a 'started' line!"
elif [[ $found == "start" ]]; then
    echo "Found a 'started' line and no errors; finished reading the file!"
else # $found is "error"
    echo "Stopped reading after an error!"
fi

答案 1 :(得分:0)

你有个好的开始。您正在检查当前正在阅读的行是否是邮件的开头("IAAS Session factory creation started"),并设置变量a以标记您已找到它!那很完美。

你在这里循环,所以它将执行if块内的所有内容,while; do将循环到下一行并再次尝试SAME if块。当然,您当前的行不再是"IAAS Session factory creation started",因此会转到else并打印"bye"

相反,您要检查您的a变量是否设置为YES,并在当前文件的迭代中执行其他操作。您将使用elif(其他如果)执行此操作。我们还可以使用elif来测试我们是否点击了消息的末尾"Communications link failure"

#!/bin/bash
filename="myXLog.txt"    
while read line
do    
  if [[ $line == "IAAS Session factory creation started" ]] ; then
    a="YES"
    echo $a
  elif [[ $a == "YES" ]; then 
    echo "ALL IS WELL" $line     
  elif [[ $line == "Communications link failure" ]] ; then
    echo "ERROR"
  else 
    echo "BYE"    
  fi
done < $filename