How to search (grep?) filename for a string and if it contains this then...

Hi i want to write a script that will search a filename e.g. test06abc.txt for a string and if it contains this string then set a variable equal to something:

something like:

var1=0

search <filename> for 06
if it contains 06 then
var1=1
else
var1=0
end if

but in unix script :slight_smile:

Hi try this

file=`find dirpath -type f -name "filename" -exec grep 06 {} \;`

if [ "$file" = "" ] ; then
var=0
else
var=1
fi

Hi! You can use grep for this.

check=`grep 06 FILENAME > /dev/null; echo $?`
if [ "$check" -eq "0" ]; then
var1=1
else
var1=0
fi

Hi,

grep has the -q or --silent option for this. Try

grep -q "test" file && a=found || a=missing

which will set $a to found if "test" was found in file. Else $a will be set to missing.

HTH Chris

When i search for a string in any file i use this:

find ./ -name "filename" | xargs grep "string_to_found"

In this way you can specify what kind of files are you searching for
"filename" or "file*" or "?ile_+.txt" or .....

it's clear and simple.