ivbtar ivbtar - 2 months ago 14
Bash Question

Linux shell script regex match

I have a text file.
I want to get lines starting with specific format.
I just want to get lines that have x/x/x format. x is a number.
But this regex is not working. It is always giving no match :

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

echo ${line}

else

echo "no match : ${line}"

fi
done <${textFileName}


File is :

enter image description here

Answer Source

Don't use bash if you can use a better tool:

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

But if you have to use bash:

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

\d is not valid regex(3).