Originally Posted by
SeijiSensei
I'd use
Code:
if [ "$(echo $LINE | grep 'four')" != "" ]
The expression "echo $LINE | grep 'four'" will match any line with the text "four" in it. If you want to be more stringent, you can use a more complex regular expression. For instance "grep 'four$'" would only match the text "four" it if came at the end of the line.
The $() operator returns the results of the command. In this case it will return the entire contents of any line containing the string 'four'. That result is tested against the empty string using the not-equal operator. So a line with the text "four" will make the LHS of the comparison not empty, and thus the entire logical expression will be true.
There is no need for the test (`[') command. The syntax of the if statement is:
Code:
if COMMANDS; then
COMMANDS
fi
POSIX:
Code:
while read -r line; do
if printf '%s' "$line" | grep "REGEX" > /dev/null 2>&1; then
printf '%s\n' "whatever"
fi
done < file
In BASH, instead of echo or printf you can use a here string:
Code:
if grep "REGEX" <<< "$LINE"; then ...
But, as suggested by Vaphell, in BASH, you can use the compound test command `[[':
Code:
if [[ $line =~ "ERE" ]]; then ...
where ERE is an extended regular expression.
See:
http://mywiki.wooledge.org/BashGuide..._and_.5B.5B.29
and BashFAQ 031.
Bookmarks