我有以下文本文件,其中包含:
12.3-456, test
test test test
如果该行包含xx.x-xxx,那么我想打印出该行。 (X是数字)
我认为我有正确的正则表达式并在此进行了测试: http://regexr.com/3clu3
然后我在bash脚本中使用了它,但是没有打印出包含文本的行。 我搞砸了什么?
#!/bin/bash
while IFS='' read -r line || [[ -n "$line" ]]; do
if [[ $line =~ /\d\d.\d-\d\d\d,/g ]]; then
echo $line
fi
done < input.txt
答案 0 :(得分:5)
您需要在Bash正则表达式中使用[0-9]
而不是\d
。不需要正则表达式分隔符,也不需要全局标记。此外,您可以使用limiting quantifiers(例如{3}
与其旁边的模式匹配3次匹配)。此外,一个点匹配正则表达式中的任何字符,因此如果要匹配文字点符号,则需要将其转义。
使用
regex="[0-9]{2}\.[0-9]-[0-9]{3},"
if [[ $line =~ $regex ]]
...
答案 1 :(得分:1)
这有效:
#!/bin/bash
#regex="/\d\d.\d-\d\d\d,/g"
regex="[0-9\.\-]+\, [A-Za-z]+"
while IFS='' read -r line || [[ -n "$line" ]]; do
echo $line
if [[ $line =~ $regex ]]; then
echo "match"
fi
done
正则表达式是[0-9中的任何一个,&#39;。&#39;,&#39; - &#39;]后跟&#39;,&#39;然后是alphachars。这可以通过多种方式进行改进 - 例如明确的地方之前/之后&#39; - &#39;。
测试表明:
$ ./sqltrace2.sh < input.txt
12.3-456, test
match
123.3-456, test
match
12.3-456,
test test test
test test test