【问题标题】:Nesting an 'if' statement in a 'for' loop to detect matching/non-matching string in a file在“for”循环中嵌套“if”语句以检测文件中的匹配/不匹配字符串
【发布时间】:2016-04-03 06:49:01
【问题描述】:

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

这是我目前所拥有的:

一个名为 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 调试中收到的输出:

+ 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

我需要改变什么来解决这个问题?

【问题讨论】:

    标签: bash loops for-loop


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多