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

标签 linux bash shell grep

如何使用 grep 在用户以字符串形式输入的文件中查找准确的单词?

例如,我需要选择要查找的词和要在其中查找它的文件。有人告诉我我真的很接近,但有些东西没有正常工作。我在 Linux 下使用 bash shell。

这是我到目前为止所做的:

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

尝试使用 -F 选项。在 shell 上键入 man grep 以获得更多详细信息。

grep -F "$word1" "$filename"

建议用引号将搜索字符串和文件名括起来,以避免因空格而导致意外输出。


不确定为什么在最后一行有 fi。不需要。

关于linux - 如何在 shell 脚本中使用 grep 在文件中查找单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19819221/

相关文章:

bash后台进程修改全局变量

string - 如何检查字符串是否包含 Bash 中的子字符串

c++ - 在 Linux 上使用 kbhit() 和 getch()

linux 添加另一个系统管理员

linux - bash:比较两个文件以附加列

python - 我如何通过终端 Linux 向程序发出特定命令?

linux - "zip -m"目录变空不删除

c++ - nm、objdump 和 pfunct 给出相互矛盾的答案来检查函数是否内联

linux - 使用 sed 替换多个单词

linux - 是否可以更改目录模式以使任何人都无法在其中创建新文件?