Skip to content
Advertisement

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

Advertisement

Answer

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).

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement