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

标签 regex bash

在 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 #

但我无法让它工作,知道吗?

最佳答案

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

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

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

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

关于regex - bash:如何检查字符串是否以 '#' 开头?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28514484/

相关文章:

bash - 将特殊字符回显到 bash 中的文件

javascript - 如何在 Node.js 脚本中获取有关 stdout 重定向文件名的信息

php - 将多个方括号值转换为数组php

正则表达式捕获从特定表达式到 Perl 中第一个空行的多行

bash - 为什么 wget -O- 输出到标准输出?

json - 创建 JSON Gist(冲突)

ios - Appledoc 无法在 Xcode 中运行

javascript - 用于验证字段的正则表达式

python - 将文本与 python 中的多个正则表达式匹配

php - 需要重新格式化 PHP Formmail 脚本中的电话号码条目