【问题标题】:bash: how to check if a string starts with '#'?bash:如何检查字符串是否以'#'开头?
【发布时间】:2015-04-15 08:57:56
【问题描述】:

在 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 正则表达式,任何引用的部分都被视为纯文本。

标签: regex bash


【解决方案1】:

如果您除了接受的答案还想在“#”前面允许空格,您可以使用

if [[ $line =~ ^[[:space:]]*#.* ]]; then
    echo "$line starts with #"
fi

有了这个

#Both lines
    #are comments

【讨论】:

    【解决方案2】:

    只需使用 == 使用 shell glob:

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

    保持# 被引用以阻止shell 试图解释为注释是很重要的。

    【讨论】:

    • 由于您使用的是[[,因此比较中只需要一个等号=
    • === 在这种情况下的行为方式相同。
    • 是的 = 也可以,但我认为 bash 开发人员支持 == 以与其他流行的编程语言兼容。
    【解决方案3】:
    while read line ; 
    do
        if [[ $line =~ ^#+ ]]; then
            echo "$line starts with #" ;
        fi
    done < data.in
    

    这样就可以用 + 删除 * + 匹配 1 个或更多 而 * 匹配 0 或更多,因此在您的代码中它会显示数字,即使它不以 '#' 开头

    【讨论】:

    • 够了:[[ $line =~ ^# ]].
    【解决方案4】:

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

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

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

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

    【讨论】:

    • 我不再完全确定[[ 规则,但$line 不应该受到双引号保护,即[[ "$line" = \#* ]]
    • @bitmask Bash 应该在使用[[ 时自动引用。
    猜你喜欢
    • 2011-01-11
    • 2019-08-24
    • 2012-02-06
    • 2023-01-01
    • 1970-01-01
    • 2011-05-04
    • 1970-01-01
    相关资源
    最近更新 更多