I am writing a bash script to search for a pattern in a file using GREP. I am clueless for why it isnt working. This is the program
echo "Enter file name...";
read fname;
echo "Enter the search pattern";
read pattern
if [ -f $fname ]; then
result=`grep -i '$pattern' $fname`
echo $result;
fi
Or is there different approach to do this ?
Thanks
(contents of file)
Welcome to UNIX
The shell is a command programming language that provides an interface to the UNIX operating system.
The shell can modify the environment in which commands run.
Simple UNIX commands consist of one or more words separated by blanks.
Most commands produce output on the standard output that is initially connected to the terminal. This output may be sent to a file by writing.
The standard output of one UNIX command may be connected to the standard input of another UNIX Command by writing the `pipe' operator, indicated by |
(pattern)
`UNIX` or `unix`
To find a pattern that is more than one word long, enclose the string with single or double quotation marks. The grep command can search for a string in groups of files. When it finds a pattern that matches in more than one file, it prints the name of the file, followed by a colon, then the line matching the pattern.
To search multiple files with the grep command, insert the filenames you want to search, separated with a space character. The terminal prints the name of every file that contains the matching lines, and the actual lines that include the required string of characters. You can append as many filenames as needed.
The grep filter searches a file for a particular pattern of characters, and displays all lines that contain that pattern. The pattern that is searched in the file is referred to as the regular expression (grep stands for global search for regular expression and print out).
We can use grep -q in combination with an if statement in order to test for the presence of a given string within a text file: $ if grep --binary-files=text -qi "insert" test_data. sql; then echo "Found!"; else echo "Not Found!"; fi Found!
The single quotes around $pattern
in the grep statement make the shell not resolve the shell variable so you should use double quotes.
Only one of those semicolons is necessary (the one before then
), but I usually omit it and put then
on a line by itself. You should put double quotes around the variable that you're echoing and around the variable holding your grep
pattern. Variables that hold filenames should be quoted, also. You can have read
display your prompt. You should use $()
instead of backticks.
read -p "Enter file name..." fname
read -p "Enter the search pattern" pattern
if [ -f "$fname" ]
then
result=$(grep -i "$pattern" "$fname")
echo "$result"
fi
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With