gpt4 book ai didi

Linux:使用 grep 在文件中查找单词,然后打印文件中是否包含该单词

转载 作者:太空宇宙 更新时间:2023-11-04 03:51:27 33 4
gpt4 key购买 nike

我正在尝试使用 grep 命令,但我不知道如何在“grep $word $file”之后继续,或者即使这可以工作。我需要做的是获取程序,以便在他们输入单词和文件后,如果该单词在文件中,程序会回显“您输入的单词在您输入的文件中”。我还需要它打印“对不起,但是您输入的单词不在您输入的文件中”如果您能提供帮助,那将非常有帮助,谢谢

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

最佳答案

使用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"

关于Linux:使用 grep 在文件中查找单词,然后打印文件中是否包含该单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26232894/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com