外壳脚本,发现由用户选择的文件中的字 [英] Shell script that finds a word within a file selected by a user

查看:140
本文介绍了外壳脚本,发现由用户选择的文件中的字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在训练做shell脚本作为一种业余爱好,我无意中发现我被我的导师给的任务。

I am training to do shell scripting as a hobby, I was stumbled on a task I was given by my tutor.

的任务是使一个shell脚本,你可以输入你想搜索中,然后,如果它存在与否它会回应一个文件名;那么,如果它存在,你有另一种选择,找到文件中的某个词,在存在一定的字必须被显示。

The task is to make a shell script that you can enter a file name you want to search in and then it will respond if it exists or not; then if it exists you have another option to find a certain word in the file that exist in there the certain word must be shown.

下面是我到目前为止已经完成。我的导师只给了我有事情做使用grep的暗示?

Here is what I've done so far. My tutor only gave me a hint it has something to do with 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

下面是我提高了工作的开始。

Here's the start of my improved work.

#!/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"

这似乎然后将该文件心不是要求我要搜索文件名后找到的单词。

It seems the file isnt then asking for the word I want to find after searching for a file name.

我在做什么错了?

阅读-p输入文件名:文件名

read -p "enter a filename:" filename

如果[[-f $文件名]

if [[ -f $ filename ]] ;

回声文件存在,那么

阅读-p输入要查找的文字:字

read -p "enter the word you want to find. : word

[grep的-c $ $字名

[grep -c $word $filename

别的回声文件$海峡不存在。
网络

else echo "the file $str doesn't exist." fi

推荐答案

解决方法一:

#!/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

有不少变种可能的。

Quite a few variants possible.

这篇关于外壳脚本,发现由用户选择的文件中的字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆