How to use grep in a shell script to find a word inside of a file

72,837

Solution 1

How can I use grep to find an exact word inside of a file entered by the user as string.

Try using -F option. Type man grep on shell for more details.

grep -F "$word1" "$filename"

It's recommended to enclose search string and file name with quotes to avoid unexpected output because of white spaces.


Not sure why you have fi on the last line. It's not needed.

Solution 2

Try:

grep -R WORD ./ to search the entire current directory, or grep WORD ./path/to/file.ext to search inside a specific file.

Solution 3

#!/bin/bash/
echo "Find the file you want to search the word in?"   
read filename  
echo "Enter the word you want to find."   
read word  
cat $filename | grep "$word"

This works fine to find the exact word match in a file.

Share:
72,837
user2957449
Author by

user2957449

Updated on July 09, 2022

Comments

  • user2957449
    user2957449 almost 2 years

    How can I use grep to find an exact word inside of a file entered by the user as string?

    For example I need to select the word I want to find and the file I want to find it in. I've been told I am really close but something is not working as it should be. I'm using bash shell under Linux.

    Here's what I've done so far:

    #!/bin/bash
    echo "Find the file you want to search the word in?"
    read filename
    echo "Enter the word you want to find."  
    read word1
    grep $word1 $filename