2017-08-17 73 views
1

我有一个文本文件。 我想要获得以特定格式开头的行。 我只想得到有x/x/x格式的行。 x是一个数字。 但是这个正则表达式不起作用。它总是给人不匹配:Linux外壳脚本正则表达式匹配

while read line   
do   
    regex="\d+\/\d+\/\d+" 
    if [[ ${line} =~ ${regex} ]]; then 

     echo ${line} 

    else 

     echo "no match : ${line}" 

    fi  
done <${textFileName} 

文件是:

enter image description here

回答

1

不要使用bash的,如果你能使用更好的工具:

grep -E '^[[:digit:]]+/[[:digit:]]+/[[:digit:]]+' "${textFileName}" 

但如果你有要使用bash:

while IFS= read -r line 
do 
    if [[ "$line}" =~ ^[[:digit:]]+/[[:digit:]]+/[[:digit:]]+ ]]; then 
    echo -- "$line" 
    else 
    echo "no match: $line" 
    fi 
done < "$textFileName" 

\d无效regex(3)

+0

嗨,我应用你的代码。但没有工作。而IFS =读-r线 做 如果[[ “$ {线}”=〜 '[[:数字:]] +/[[:数字:]] +/[[:数字:]] +' ]];然后 echo - “X:$ line” else echo“no match:$ line” fi done <“$ textFileName” – ivbtar

+0

不要引用正则表达式 –