在用户选择的文件中查找单词的Shell脚本
我正在训练做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“输入文件名:”文件名
如果[[-f $ filename]];
那么echo“文件名存在”
阅读-p“输入你想找的单词。:单词
[grep -c $ word $ filename
否则回显“文件$ str不存在”。 科幻
一个解决方案
#!/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
只有几个变种可能。
你可以通过以下方式来完成单词计数部分
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放在$()中让我们将结果存储在一个变量中。 我认为其余的是不言自明的,尤其是,你已经在你的文章:)
尝试,
 # 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
上一篇: Shell script that finds a word within a file selected by a user
