【发布时间】: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
我需要改变什么来解决这个问题?
【问题讨论】: