Read file line by line with bash script

I need a bash script to read a file line by line. If the regular expression matches, highlight this line.

script:

#!/bin/bash

echo "Start!"

for line in $(cat results)
do
   regex = '^[0-9]+/[0-9]+/[0-9]+$'
   if [[ $line =~ $regex ]]
   then
      echo $line
   fi
done

It prints the contents of the file, but shows this warning:

./script: line 7: regex: command not found

Where is the mistake?

+3
source share
3 answers

The problem in this case is the spaces around the character =inregex = '^[0-9]+/[0-9]+/[0-9]+$'

It should be

regex='^[0-9]+/[0-9]+/[0-9]+$'

ShellCheck automatically warns you about this, and also offers where to specify your variables and how to read line by line (you are currently doing this word by word).

+4
source

. :

#!/bin/bash

regex='[0-9]'

while read line
do
    if [[ $line =~ $regex ]]
    then
        echo $line
    fi
done < input
+6

:

regex='^[0-9]+/[0-9]+/[0-9]+$'
+1

All Articles