在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 #
但是我不能让它工作,你知道吗?
发布于 2015-02-14 18:12:42
不需要正则表达式,一个模式就足够了
if [[ $line = \#* ]] ; then
echo "$line starts with #"
fi
或者,您可以使用参数扩展:
if [[ ${line:0:1} = \# ]] ; then
echo "$line starts with #"
fi
发布于 2015-02-14 18:12:05
只需使用==
即可使用shell glob
line='#foo'
[[ "$line" == "#"* ]] && echo "$line starts with #"
#foo starts with #
保持对#
的引用是很重要的,以阻止shell试图解释为注释。
发布于 2015-02-14 18:10:12
while read line ;
do
if [[ $line =~ ^#+ ]]; then
echo "$line starts with #" ;
fi
done < data.in
这将完成删除* with ++匹配1或更多,而*匹配0或更多,因此在您的代码中,它将显示数字,即使它不是以'#‘开头
https://stackoverflow.com/questions/28514484
复制相似问题