tags:

views:

88

answers:

2

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`
+5  A: 

The single quotes around $pattern in the grep statement make the shell not to resolve the shell variable. Use double quotes.

Moritz Both
tried this, but its displaying me only last 2 lines. The file contains 5 lines and the
atif089
as paxdiablo said, please post the content of the file and your $pattern.
Moritz Both
+1  A: 

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
Dennis Williamson