在'for'循环中嵌套'if'语句以检测文件中的匹配/非匹配字符串

时间:2016-04-03 06:49:02

标签: bash loops for-loop

我想逐行搜索文件,并在匹配字符串时将一条给定的消息打印到屏幕上,当字符串不匹配时,将不同的消息打印到屏幕上。

这是我到目前为止所做的:

名为 network.txt 的文件,该文件位于运行脚本的同一目录中。这是文件的内容:

am.12345
XXXXXXXX
am.67890
XXXXXXXX

这是剧本:

#!/bin/bash
file="network.txt"
for line in `cat $file`
  do
    if [ $line == am.* ]
      then
         echo $line
    elif [ $line != am.* ]
      then
         echo "We couldn't find what you were looking for"
    fi
done

这是我从bash debug收到的输出:

+ file=network.txt
++ cat network.txt
+ for line in '`cat $file`'
+ '[' am.12345 == 'am.*' ']'
+ '[' am.12345 '!=' 'am.*' ']'
+ echo 'We couldn'\''t find what you were looking for'
We couldn't find what you were looking for
+ for line in '`cat $file`'
+ '[' XXXXXXXX == 'am.*' ']'
+ '[' XXXXXXXX '!=' 'am.*' ']'
+ echo 'We couldn'\''t find what you were looking for'
We couldn't find what you were looking for
+ for line in '`cat $file`'
+ '[' am.67890 == 'am.*' ']'
+ '[' am.67890 '!=' 'am.*' ']'
+ echo 'We couldn'\''t find what you were looking for'
We couldn't find what you were looking for
+ for line in '`cat $file`'
+ '[' XXXXXXXX == 'am.*' ']'
+ '[' XXXXXXXX '!=' 'am.*' ']'
+ echo 'We couldn'\''t find what you were looking for'
We couldn't find what you were looking for

但是当我运行脚本时,我没有得到预期的行为:

macbook:~ enduser$ ./network.sh
We couldn't find what you were looking for
We couldn't find what you were looking for
We couldn't find what you were looking for
We couldn't find what you were looking for

我相信输出应该如下所示:

am.12345
We couldn't find what you were looking for
am.67890
We couldn't find what you were looking for

我需要更改以解决此问题?

1 个答案:

答案 0 :(得分:0)

您需要使用[[ $line =~ am.* ]]

智能匹配或regular expression比较使用Perl =~运算符,而不是==编码。 RTFM了解详情。 (搜索=~。)