检查文件中的行是否包含Bash中的模式

时间:2013-12-16 01:33:52

标签: string bash

我试图找出为什么这不会检查文件中的行并回显 你如何比较或检查字符串是否包含某些内容?

#!/bin/bash
while read line
do 
    #if the line ends 
    if [[ "$line" == '*Bye$' ]] 
    then
    :
        #if the line ends 
    elif [[ "$line" == '*Fly$' ]] 
    then
        echo "\*\*\*"$line"\*\*\*"
    fi
done < file.txt

2 个答案:

答案 0 :(得分:3)

问题是*Bye$不是shell模式(shell模式不使用$表示法,它们只使用尾随{{1}的 lack }) - 即使它是,将它放在单引号中将禁用它。相反,只需写下:

*

(同样适用于 if [[ "$line" == *Bye ]] )。

答案 1 :(得分:2)

如果您想使用正确的正则表达式,可以使用=~运算符完成,例如:

if [[ "$line" =~ Bye$ ]]

使用==从shell模式获得的有限正则表达式不包括终点标记$等内容。

请注意,您可以使用shell模式(*Bye)执行此操作,但是,如果您想要正则表达式的全部功能(或者甚至只是一致的表示法),=~是通往去。