'Finding multiple strings in shell scripts
I am trying to find strings Error:, Error :, ERROR:, ERROR : in a given file, if found then go to if block if not found then go to else block.
Below is the logic I had written to perform this operation.
#!/bin/bash
file='file.log'
text=`cat $file`
echo $text
if [[ ${text} = *Error:* ||${text} = *ERROR:*|| ${text} = *ERROR :* || ${text} = *Error :* || $? -ne 0 ]]; then
STATUS=1
echo "=> string found."
else
echo "=> no string found."
fi
Seems like this logic is having issues as its returning below error.
syntax error near `:*'
Can someone please help me in resolving this issue?
Solution 1:[1]
The pattern you’re looking for is easily expressed in a regex, so you can just use grep:
#!/bin/bash
file='file.log'
if grep -iq 'error \{0,1\}:' "${file}"
then
STATUS=1
echo "=> string found."
else
echo "=> no string found."
fi
There’s no need to read the whole file into a variable, nor to check $? explicitly.
Solution 2:[2]
This is easier to do using grep, using -i for case insensitive matching and -q to suppress output:
#!/bin/bash
file='file.log'
if grep -iq 'error \?:' "$file"; then
STATUS=1
echo "=> string found."
else
echo "=> no string found."
fi
The regular expression error ?: means: the text error, followed by an optional space (indicated by \? after the space), followed by :.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Biffen |
| Solution 2 |
