我有以下文本文件,其中包含:
12.3-456, test
test test test
Run Code Online (Sandbox Code Playgroud)
如果该行包含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
Run Code Online (Sandbox Code Playgroud)
您需要使用[0-9]而不是使用\dBash正则表达式.不需要正则表达式分隔符,也不需要全局标记.此外,您可以使用限制量词(例如{3},它将匹配旁边的模式的3次出现)来收缩它.此外,一个点匹配正则表达式中的任何字符,因此如果要匹配文字点符号,则需要将其转义.
使用
regex="[0-9]{2}\.[0-9]-[0-9]{3},"
if [[ $line =~ $regex ]]
...
Run Code Online (Sandbox Code Playgroud)