Bash脚本使用Grep搜索文件中的模式

时间:2010-06-16 11:38:08

标签: bash unix grep

我正在编写一个bash脚本,使用GREP在文件中搜索模式。我无法解释为什么它不起作用。这是程序

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

或者有不同的方法来做到这一点吗?

由于


(文件内容)

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 |

(图案)

`UNIX` or `unix`

3 个答案:

答案 0 :(得分:18)

grep语句中$pattern周围的单引号使shell无法解析shell变量,所以你应该使用双引号。

答案 1 :(得分:4)

只需要其中一个分号(then之前的分号),但我通常会省略它并将then单独放在一行上。您应该在您回显的变量周围加上双引号,并在包含grep模式的变量周围。还应引用包含文件名的变量。您可以read显示提示。您应该使用$()而不是反对。

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

答案 2 :(得分:0)

读取-p“输入文件名...”fname 读取-p“输入搜索模式”模式 如果[-f“$ fname”] 然后     result = $(grep -i -v -e $ pattern -e“$ fname”)     回声“$ result” 网络