[英]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? 如何使用grep在用户输入的文件中找到一个确切的单词作为字符串?
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. 我在Linux下使用
bash
shell。
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.
如何使用grep在用户输入的文件中找到一个确切的单词作为字符串。
Try using -F
option. 尝试使用
-F
选项。 Type man grep
on shell for more details. 在shell上键入
man grep
以获取更多详细信息。
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. 不知道为什么你在最后一行有
fi
。 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. grep -R WORD ./
用于搜索整个当前目录,或者用grep WORD ./path/to/file.ext
搜索特定文件。
#!/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"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.