Reputation: 342
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
Reputation: 3162
Elimnate the spaces around regex:
regex='^[0-9]+/[0-9]+/[0-9]+$'
Upvotes: 1
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
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