Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex Shell脚本:if语句中的正则表达式_Regex_Shell_If Statement - Fatal编程技术网

Regex Shell脚本:if语句中的正则表达式

Regex Shell脚本:if语句中的正则表达式,regex,shell,if-statement,Regex,Shell,If Statement,我似乎不知道如何在if语句中正确地编写正则表达式。我想让它打印出所有带有“结束日期”的行 数字包含具有以下内容的文本文件: 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

我似乎不知道如何在if语句中正确地编写正则表达式。我想让它打印出所有带有“结束日期”的行

数字包含具有以下内容的文本文件:

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 
以下是我遇到问题的代码片段:

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
if[-f$number]
然后
读行时
做
如果[$line=^End]
然后
回音“$line”
其他的
回声“坏了!”
打破
fi
完成<$number
其他的
echo“=======$NUMBERS读取失败=====”
fi
输出为:

坏了


如果您正在使用bash,请尝试
=~

...
if [[ $line =~ ^End ]]
请注意,以下操作不起作用:


您可以使用以下命令检查
是否以
结束
开头

if [[ "$line" == End* ]]
如果要使用正则表达式,可以使用以下命令

if [[ "$line" =~ ^End* ]]

还请注意,建议始终引用变量


可移植的解决方案是使用支持通配符(全局通配符;不是实际的正则表达式)的
case
。语法有点奇怪,但你会习惯的

while read -r line; do
    case $line in
        End*) ... your stuff here 
            ... more your stuff here
            ;;   # double semicolon closes branch
    esac
done

请注意,这并非可移植到所有shell。@datgay“=~”做什么?@dalawh
=~
告诉bash匹配正则表达式而不是文本字符串。对于这样简单的东西,您不需要正则表达式:
[$line==End*]
您的文件是否在每行开头都包含
字符?@glennjackman我正在为带日期的字符执行正则表达式,但它不起作用,所以我在第一行执行了正则表达式,以确保没有出错。实际文件不包含“>”。我认为=和==之间没有区别。有?另外,使用一个[]和两个[]有什么区别?
如果[“$a”=“$b”]
进行字符串比较,但是
==
[[]
可以用于正则表达式搜索。请看我在答案中给出的链接。希望能有帮助。从该链接复制--“比较运算符==在双括号测试中的行为与在单括号测试中的行为不同。”你能给我看看你的代码吗,它应该可以工作……我已经测试过了。@dalawh我有一个小的打字错误。我更新了答案。请使用
End*
并查看是否有效。
[
是基本的旧Bourne
sh
命令
test
,它不支持正则表达式。
[
变体是一个Bash(和
ksh
等)扩展具有更高的健壮性和更多的功能,包括
=~
正则表达式匹配。正确的字符串相等运算符是
=
,尽管Bash允许
=
作为别名。@cnst确实,这应该可以移植到原始的Bourne
sh
。(对于
csh
,没有任何保证,有些*BSD变体似乎仍在莫名其妙地珍视它。)
while read -r line; do
    case $line in
        End*) ... your stuff here 
            ... more your stuff here
            ;;   # double semicolon closes branch
    esac
done