Shell脚本,用于在用户选择的文件中查找单词

时间:2013-11-05 18:00:44

标签: linux bash shell grep

我正在训练将shell脚本作为一种爱好,我偶然发现了我的导师给我的任务。

任务是创建一个shell脚本,您可以输入要搜索的文件名,然后它将响应(如果存在或不存在);然后,如果它存在,你有另一种选择,在文件中找到某个单词,必须显示某个单词。

这是我到目前为止所做的。我的导师只给了我一个提示,它与grep有关?

#!/bin/bash

echo "search the word you want to find"

read strfile

echo "Enter the file you wish to search in"
grep $strfile 

"strword" strfile

这是我改进工作的开始。

#!/bin/bash

printf "Enter a filename:
"
read str
 if [[ -f "$str" ]]; then

echo "The file '$str' exists."

else

echo "The file '$str' does not exists"

在搜索文件名后,文件似乎没有要求我找到的单词。

我做错了什么?

!/斌/庆典

读取-p“输入文件名:”filename

if [[-f $ filename]];

回显“文件名存在”然后

读取-p“输入您要查找的单词。:word

[grep -c $ word $ filename

else echo“文件$ str不存在。” 网络

3 个答案:

答案 0 :(得分:4)

一个解决方案:

#!/bin/bash

read -p "Enter a filename: " filename

if [[ -f $filename ]] ; then
    echo "The file $filename exists."
    read -p "Enter the word you want to find: " word
    grep "$word" "$filename"
else
    echo "The file $filename does not exist."
fi

可能有多种变体。

答案 1 :(得分:0)

你可以通过以下方式进行单词计数:

exits=$(grep -c $word $file)
if [[ $exists -gt 0 ]]; then
    echo "Word found"
fi

这就是你所缺少的,你的其余部分都可以。

“grep -c”计算包含$ word的行,所以文件为:

word word other word
word
nothing

将产生值“2”。将grep放在$()中让你将结果存储在变量中。我认为其余部分是不言自明的,特别是你已经在帖子中发布了:))

答案 2 :(得分:0)

尝试,

 # cat find.sh
 #!/bin/bash
 echo -e "Enter the file name:"
 read fi
 echo -e "Enter the full path:"
 read pa
 se=$(find "$pa" -type f -name "$fi")
 co=$(cat $se | wc -l)
 if [ $co -eq 0 ]
 then
 echo "File not found on current path"
 else
 echo "Total file found: $co"
 echo "File(s) List:"
 echo "$se"
 echo -e "Enter the word which you want to search:"
 read wa
 sea=$(grep -rHn "$wa" $se)
 if [ $? -ne 0 ]
 then
 echo "Word not found"
 else
 echo "File:Line:Word"
 echo "$sea"
 fi
 fi

输出:

 # ./find.sh
 Enter the file name:
 best
 Enter the full path:
 .
 Total file(s) found: 1
 File(s) List:
 ./best
 Enter the word which you want to search:
 root
 File:Line:Word
 ./best:1:root
 # ./find.sh
 Enter the file name:
 besst
 Enter the full path:
 .
 File not found on current path
相关问题