我正在接受培训,将编写 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"
在搜索文件名后,文件似乎并没有要求我要查找的词。
我做错了什么?
!/bin/庆典
read -p "enter a filename:"文件名
如果 [[ -f $ 文件名]] ;
echo "文件名存在"然后
read -p "输入要查找的词。:word
[grep -c $word $文件名
else echo "文件 $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
可能有很多变体。
关于linux - 在用户选择的文件中查找单词的 Shell 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19795643/