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

use*_*449 3 linux bash shell grep

如何使用grep在用户输入的文件中找到一个确切的单词作为字符串?

例如,我需要选择我想要找到的单词和我想要找到的文件.我被告知我非常接近,但有些东西不能正常工作.我bash在Linux下使用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
Run Code Online (Sandbox Code Playgroud)

jks*_*hah 6

如何使用grep在用户输入的文件中找到一个确切的单词作为字符串.

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

grep -F "$word1" "$filename"
Run Code Online (Sandbox Code Playgroud)

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


不知道为什么你fi在最后一行.这不是必需的.