3

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
1
  • 1
    You seem to be looking for the -F option for grep.
    – devnull
    Nov 6, 2013 at 18:08

4 Answers 4

6

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.

1

Try:

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

1
  • 2
    Welcome to Stack Overflow. Please read the About page soon. While the information you added about -R is new, it is not clear that it is relevant to the context of the question. The 'or' information is already understood. In short, you've not added anything useful to the information already available. You're at liberty to add such answers, but they're relatively unlikely to be upvoted and may earn you downvotes. When you add a new answer to an old question with existing answers, please make sure you're adding something distinctive and new that's relevant. Jul 11, 2016 at 2:07
1
#!/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.

0

If you want an exact word match within lines use
grep "\b$word\b"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.