Reputation: 51
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
Upvotes: 3
Views: 83546
Reputation: 21
If you want an exact word match within lines use
grep "\b$word\b"
Upvotes: 0
Reputation: 191
#!/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.
Upvotes: 1
Reputation: 27
Try:
grep -R WORD ./
to search the entire current directory, or grep WORD ./path/to/file.ext
to search inside a specific file.
Upvotes: 1
Reputation: 11703
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.
Upvotes: 6