Linux 如何在 shell 脚本中使用 grep 在文件中查找单词

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19819221/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 01:17:06  来源:igfitidea点击:

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

linuxbashshellgrep

提问by user2957449

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 bashshell under Linux.

例如,我需要选择我想查找的单词和我想在其中找到它的文件。有人告诉我我真的很接近但有些东西没有正常工作。我bash在 Linux 下使用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

回答by jkshah

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

如何使用 grep 在用户作为字符串输入的文件中查找确切的单词。

Try using -Foption. Type man grepon shell for more details.

尝试使用-F选项。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 fion the last line. It's not needed.

不知道你为什么fi在最后一行。不需要。

回答by John McLane

Try:

尝试:

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

grep -R WORD ./搜索整个当前目录,或grep WORD ./path/to/file.ext搜索特定文件。

回答by Sushmita Konar

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

这可以很好地在文件中找到精确的单词匹配。

回答by user6371909

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

如果您想在行精确匹配单词,请使用
grep "\b$word\b"