I have a bash script. I need to look if "text" exists in the file and do something if it exists.
Thanks in advance
I have a bash script. I need to look if "text" exists in the file and do something if it exists.
Thanks in advance
Something like the following would do what you need.
grep -w "text" file > /dev/null
if [ $? -eq 0 ]; then
#Do something
else
#Do something else
fi
cat <file> | grep <"text">
and check the return code with test $?
Check out the excellent: Advanced Bash-Scripting Guide
If you need to execute a command on all files containing the text, you can combine grep
with xargs
. For example, this would remove all files containing "yourtext":
grep -l "yourtext" * | xargs rm
To search a single file, use if grep ...
if grep -q "yourtext" yourfile ; then
# Found
fi
You can put the grep
inside the if
statement, and you can use the -q
flag to silence it.
if grep -q "text" file; then
:
else
:
fi
just use the shell
while read -r line
do
case "$line" in
*text* )
echo "do something here"
;;
* ) echo "text not found"
esac
done <"file"