Shell script that finds a word within a file selec

2019-09-05 08:44发布

问题:

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

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.

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.

What am I doing wrong?

!/bin/bash

read -p "enter a filename:" filename

if [[ -f $ filename ]] ;

echo " the filename exists " then

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

[grep -c $word $filename

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

回答1:

One solution:

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



回答2:

You can do the word counting part by:

exits=$(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 :)



回答3:

Try,

 # 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

output:

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