Linux:使用grep在文件中查找单词,然后打印,如果它在文件中有或没有该单词

时间:2014-10-07 09:33:41

标签: linux string bash grep find

我正在尝试使用grep命令但是我不知道如何继续" grep $ word $ file"或者即使这样也行。我需要做的是获取程序,以便在他们输入单词和文件之后如果单词在文件中,则程序回显"您输入的单词在您拥有的文件中输入&#34。我也需要它来打印"我很抱歉,但您输入的单词不在您输入的文件中#34;如果你能提供帮助,那将非常有用,谢谢你

#!/bin/bash
echo "Welcome what please type in what you would like to do!"
echo "You can:"
echo "Search for words in file type (S)"
echo "Quit (Q)"
read option
while $option in
    do
            S)      echo "What is the name of the file you would like to search for?"
                    read file
                    echo "What word would you like to find in the file?"
                    read word
                    grep $word $file


            Q)      echo "Goodbye!"
                    exit
    esac
done

2 个答案:

答案 0 :(得分:0)

使用grep -q选项禁用匹配单词的打印,并使用echo $?获取grep的返回值。如果找到匹配项,则0是返回值,否则将返回1

#!/bin/bash
echo "Welcome what please type in what you would like to do!"
echo "You can:"
echo "Search for words in file type (S)"
echo "Quit (Q)"
read option
case $option in
            S)      echo "What is the name of the file you would like to search for?"
                    read file
                    echo "What word would you like to find in the file?"
                    read word
                    grep -q $word $file
                    if [ $? -eq 0 ]; then
                      echo "$word found in $file"
                    else
                      echo "$word NOT found in $file"
                    fi
                    ;;


            Q)      echo "Goodbye!"
                    exit
esac

如果您想匹配整个单词,也可以使用grep -w。因此,grep看起来像

                grep -wq $word $file
                if [ $? -eq 0 ]; then
                  echo "$word found in $file"
                else
                  echo "$word NOT found in $file"

答案 1 :(得分:0)

使用&&||

的简单一行
grep -q $word $file && echo "found the word" || echo "not found the word"

例如

$ echo hello | grep -q hell && echo "found the word" || echo "not found the word"
found the word

$ echo hello | grep -q help && echo "found the word" || echo "not found the word"
not found the word