Read lines and match against pattern
Here's a quickie for you, simply what we're doing is
Line 1: While reading file into variable line
Line 2: Match a regex, echo the $line
if matching the word "bird" echo that line. Do whatever actions you need here, in this if statement.
Line 3: End of while loop, which pipes in the file foo.text
#!/bin/bash
while read line; do
if [[ $line =~ bird ]] ; then echo $line; fi
done <foo.text
Note that "bird" is a regex. So that you could replace it with for example: bird.*word
to match the same line with a regular expression.
Try it with a file like so, called foo.text
with the contents:
my dog is brown
her cat is white
the bird is the word
The easier way to do this, is using grep
(or egrep
).
grep bird file.txt