search and Replace

hello,

How to search a Word in a shell file and if that exists echo that the word exists and stop that operation and if that doesn't exists then echo word not found.

Thanks in advance.

Bye

#!/bin/sh
# check.sh
# This script takes two arguments -
# The first is the word you a looking for,
# and the second is the file you want to find
# the word in.
# Example: check.sh lamb haggis
# Will look for the word "lamb" in the file "haggis"
if [ "$#" -ne "2" ] ; then
     echo "Usage: "
     echo "`basename $0` {search string} {file} "
     exit 2
fi
if [ -f "$2" ] ; then
grep "$1" $2 > /dev/null 
case $? in
     0) echo -e "\nThe word \"$1\" was found in the \"$2\" file! \n" ;;
     *) echo -e "\nThe word \"$1\" was NOT found in the \"$2\" file! \n" ;;
esac
exit 0
else
echo "The \"$2\" file does not exist"
exit 2
fi

This is one of many ways to do it...

I was just thinking about it, and I guess this isn't the most helpful was to explain this. I'm going to add some comments (in bold) to the code, so you can see what's happening step by step:

By saying this is one of many, I mean it - here is an example of a one-liner that will do nearly the same thing without the error handling or variables:

grep lamb haggis > /dev/null && echo Word found in file || echo Word NOT found in file 

As you can see, the "grep" command is the same as in the script, but the messages are handled differently. The commands after the "&&" will execute if the previous command was successful, and the command after the "||" will execute if it was not successful.

Geez, I'd make a horrible teacher...

hello,

consider searching a word without passing any parameter , but only giving single constant word and single file.

thanks.

Well, if you want to hard-code the names into the script, that would be even easier...

#!/bin/sh
grep {your_word} {file} > /dev/null && echo "Word found" || echo "Word not found"

Very similar to the example I gave above, simply insert into a file and execute...