Saturday, February 19, 2022

[SOLVED] Using grep inside a script

Issue

I'm trying to search a file to find a word using grep. I'm trying to use it inside of a script but I am unable to get it to work. I'm a beginner at this so my code is probably not good. Here's what I have so far

#!/bin/bash
echo "apple", "book", "cat" >> file.txt

read -r filename
filename='file.txt'
"$4"=filename
"$1"=grep
"$2"=-R

So ideally I want the user to be able to type the name of the script on the command line along with the word they are searching for, which in this case would be "book".

user:~/dir$ ./wordfind.sh book

I may be doing this completely wrong, but when I run the above in the command line, it freezes and I have to Ctrl-Z to get out of it. Thanks.


Solution

The question is not clear enough.

This answer assumes that you want to call your script with a string or regex as the first argument, i.e. the search term must be quoted if it contains spaces or special characters.

You could change the script wordfind.sh to

#!/bin/bash

# note: I changed >> to > here to avoid duplicating the data on repeated calls
echo "apple", "book", "cat" > file.txt
echo "dad", "food", "girl" >> file.txt
echo "god", "hey", "linux" >> file.txt
echo "out", "owl", "rice" >> file.txt
echo "say", "toy", "zebra" >> file.txt

# Check if exactly one argument was specified.
if [ $# -ne 1 ]
then
   echo "usage: $0 'regex'"
   exit 1
fi

grep "$1" file.txt

Examples:

$ ./wordfind.sh rice
out, owl, rice

$ ./wordfind.sh 'z.*a'
say, toy, zebra

$ ./wordfind.sh 'd, f'
dad, food, girl



Answered By - Bodo
Answer Checked By - Gilberto Lyons (WPSolving Admin)