[英]Shell Scripting: RegEx in if Statement
I can't seem to figure out how to write a regex correctly in an if statement. 我似乎无法弄清楚如何在if语句中正确编写正则表达式。 I wanted it to print out all the lines with "End Date" in it. 我希望它打印出所有带有“结束日期”的行。
NUMBERS contains a text file with the following content: NUMBERS包含一个包含以下内容的文本文件:
End Date ABC ABC ABC ABC ABC ABC
05/15/13 2 7 1 1 4 5
04/16/13 4 3 0 1 3 6
03/17/13 6 9 3 8 5 9
02/18/13 8 2 7 1 0 1
01/19/13 1 9 2 2 5 2
12/20/12 7 2 7 1 0 1
Here is a snippet of my code that I am having problems with: 以下是我的代码片段,我遇到了以下问题:
if [ -f $NUMBERS ]
then
while read line
do
if [ $line = ^End ]
then
echo "$line"
else
echo "BROKEN!"
break
fi
done < $NUMBERS
else
echo "===== $NUMBERS failed to read ====="
fi
The output is: 输出是:
Broken! 破碎!
The portable solution is to use case
which supports wildcards (glob wildcards; not actual regular expressions) out if the box. 便携式解决方案是使用case
,其支持通配符(水珠通配符;不实际正则表达式)出来,如果框。 The syntax is slightly freaky, but you get used to it. 语法略显怪异,但你已经习惯了。
while read -r line; do
case $line in
End*) ... your stuff here
... more your stuff here
;; # double semicolon closes branch
esac
done
You can use the following to check if the line
begins with End
您可以使用以下内容检查该line
是否以End
开头
if [[ "$line" == End* ]]
You can use the following if you want to use regex. 如果要使用正则表达式,可以使用以下内容。
if [[ "$line" =~ ^End* ]]
http://tldp.org/LDP/abs/html/comparison-ops.html http://tldp.org/LDP/abs/html/comparison-ops.html
Also note that it is recommended to always quote your variables. 另请注意,建议始终引用您的变量。
http://tldp.org/LDP/abs/html/quotingvar.html http://tldp.org/LDP/abs/html/quotingvar.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.