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
One solution:
Quite a few variants possible.
Try,
output:
You can do the word counting part by:
That's what you're missing, the rest of your script is ok.
"grep -c" counts lines which contain $word, so a file:
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 :)