0

我正在训练做 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/bash

read -p "输入文件名:" 文件名

如果 [[ -f $ 文件名]] ;

echo "文件名存在" 然后

read -p "输入你要查找的单词。:word

[grep -c $word $文件名

else echo "文件 $str 不存在。" 菲

4

3 回答 3

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

可能有相当多的变体。

于 2013-11-05T18:43:38.393 回答
1

You can do the word counting part by:

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

That's what you're missing, the rest of your script is ok.

"grep -c" counts lines which contain $word, so a file:

word word other word
word
nothing

will produce value "2". Putting grep in $() let's you store the result in a variable. I think the rest is self-explanatory, especially, that you already have it in you post :)

于 2013-11-05T19:02:46.090 回答
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
于 2013-11-05T20:11:55.773 回答