I have a bash script. I need to look if "text" exists in the file and do something if it exists.
Thanks in advance
From stackoverflow
-
grep is your friend here
-
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 fiPaul Creasey : I prefer `if [ $(grep -c "text" file) -gt 0 ]` but it the same thing.Gordon Davisson : Martin's approach (with `grep -q`) is both faster (doesn't search entire file, just up to the first match) and (IMHO) cleaner than either of these approaches. -
cat <file> | grep <"text">and check the return code withtest $?Check out the excellent: Advanced Bash-Scripting Guide
-
If you need to execute a command on all files containing the text, you can combine
grepwithxargs. For example, this would remove all files containing "yourtext":grep -l "yourtext" * | xargs rmTo search a single file, use
if grep ...if grep -q "yourtext" yourfile ; then # Found fi -
You can put the
grepinside theifstatement, and you can use the-qflag 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"
0 comments:
Post a Comment