我正在训练编写 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"
搜索文件名后,文件似乎并没有询问我想要查找的单词。
我做错了什么?
read -p“输入文件名:”文件名
if [[ -f $ 文件名 ]] ;
echo“文件名存在”然后
read -p "输入你要查找的单词。:单词
[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
可能有很多变体。
您可以通过以下方式进行字数统计:
exists=$(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
#!/bin/bash
read -p“输入文件名:”文件名
if [ -f $文件名 ] 然后 echo "文件 $filename 存在。" read -p "输入你要查找的单词:" word 结果=
grep -o "$word" $filename
echo "输入的单词是 '$result' 存在于 '$filename' 中"
别的
echo "文件 $filename 不存在。"
菲