Bash:如何检查字符串是否以 '#' 开头?

27
在bash中,我需要检查一个字符串是否以'#'符号开头。我该怎么做?
这是我的做法--
if [[ $line =~ '#*' ]]; then
    echo "$line starts with #" ;
fi

我想在一个文件上运行这个脚本,文件看起来像这样--

03930
#90329
43929
#39839

这是我的脚本 --

while read line ; do
    if [[ $line =~ '#*' ]]; then
        echo "$line starts with #" ;
    fi
done < data.in

这是我期望的输出 --

#90329 starts with #
#39839 starts with #

但是我无法让它工作,有什么想法吗?


使用bash正则表达式时,任何带引号的部分都被视为纯文本。 - glenn jackman
4个回答

45

不需要正则表达式,只需要一个模式就够了

if [[ $line = \#* ]] ; then
    echo "$line starts with #"
fi

或者,您可以使用参数扩展:

if [[ ${line:0:1} = \# ]] ; then
    echo "$line starts with #"
fi

1
我对[[规则不是很确定了,但是$line应该加上双引号保护,即[[ "$line" = \#* ]],对吗? - bitmask
1
@bitmask Bash在使用[[时应自动引用。 - Philipp Claßen

6

只需使用 shell glob,并使用 ==

line='#foo'
[[ "$line" == "#"* ]] && echo "$line starts with #"
#foo starts with #

重要的是要将#引用,以防止shell尝试将其解释为注释。

由于您正在使用 [[,因此在比较中只需要一个等号 = - Potherca
在这种情况下,“=”和“==”的行为方式相同。 - anubhava
1
是的,= 也可以使用,但我认为Bash开发人员支持使用 == 以便与其他流行的编程语言兼容。 - anubhava

4
如果你希望在接受的答案之外,允许在“#”前使用空格,那么可以使用以下方法:
if [[ $line =~ ^[[:space:]]*#.* ]]; then
    echo "$line starts with #"
fi

通过这个

#Both lines
    #are comments

1
while read line ; 
do
    if [[ $line =~ ^#+ ]]; then
        echo "$line starts with #" ;
    fi
done < data.in

这将起到作用,使用+替换*即可。 +匹配1个或多个,而*匹配0个或多个。因此,在您的代码中,即使数字不以“#”开头,它也会显示出来。

3
只需这样做:[[ $line =~ ^# ]] - gniourf_gniourf

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接