Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash script - Check if a file contains a specific line

I need to check if a file contains a specific line. This file is written continuously by someone, so I put the check inside a while loop.

FILE="/Users/test/my.out"
STRING="MYNAME"
EXIT=1
while [ $EXIT -ne 0 ]; do 
    if [ -f $FILE ] ; then CHECK IF THE "STRING" IS IN THE FILE - IF YES echo "FOUND"; EXIT=0; fi
done

The file contains text and multiple lines.

like image 767
user3472065 Avatar asked Apr 04 '14 11:04

user3472065


People also ask

How do you check if a file contains a specific string?

Just run the command directly. Add -q option when you don't need the string displayed when it was found. The grep command returns 0 or 1 in the exit code depending on the result of search.


1 Answers

if $FILE contains the file name and $STRING contains the string to be searched, then you can display if the file matches using the following command:

if [ ! -z $(grep "$STRING" "$FILE") ]; then echo "FOUND"; fi
like image 86
fstab Avatar answered Sep 19 '22 13:09

fstab