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 开发者_JS百科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`
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
read -p "Enter file name..." fname
read -p "Enter the search pattern" pattern
if [ -f "$fname" ]
then
result=$(grep -i -v -e $pattern -e "$fname")
echo "$result"
fi
精彩评论