araujophillips
araujophillips

Reputation: 342

Read file line by line with bash script

I need a bash script to read a file line by line. If a regex match, echo this line.

The script is the following:

#!/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 is printing the file content, but show this warning:

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

Where is the error?

Upvotes: 5

Views: 11824

Answers (3)

Stepan Grigoryan
Stepan Grigoryan

Reputation: 3162

Elimnate the spaces around regex:

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

Upvotes: 1

that other guy
that other guy

Reputation: 123450

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

It should be

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

ShellCheck automatically warns you about this, and also suggests where to quote your variables and how to read line by line (you're currently doing it word by word).

Upvotes: 4

Fredrik Pihl
Fredrik Pihl

Reputation: 45652

Others have given you hints about the actual regexp to use. The proper way to loop over all the lines in a file is this:

#!/bin/bash

regex='[0-9]'

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

Upvotes: 8

Related Questions