2010-06-16 79 views
8

我正在编写一个bash脚本来使用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` 
+0

grep应该是管道afaik,所以'ls -l |例如,grep'^ d''将返回当前位置中的所有目录... – deostroll 2010-06-16 11:42:28

+1

grep将从文件名列表或通配符开始工作。它不必管道。 – Curtis 2010-06-16 11:43:57

+0

您的模式是否包含需要转义的字符? – 2010-06-16 11:58:21

回答

15

各地$pattern单引号在grep的声明使外壳不能解决壳变量,所以你应该使用双引号。

+0

试过这个,但它只显示我最后2行。该文件包含5行和 – 2010-06-16 11:46:54

+0

paxdiablo说,请张贴文件的内容和你的$模式。 – 2010-06-16 12:13:58

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 
0

读-p “输入文件名......” FNAME 读-p “输入搜索模式” 模式 如果[-f “$ FNAME”] 然后 结果= $(grep的-i -v -e $ pattern -e“$ fname”) echo“$ result” fi

+1

请在您的文章中使用codeformat – 2017-11-16 14:04:38