简体   繁体   中英

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

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

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.

Try:

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

#!/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.

如果你想在行内使用精确的单词匹配
grep "\\b$word\\b"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM