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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3052867/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 19:22:01  来源:igfitidea点击:

Bash Script using Grep to search for a pattern in a file

bashunixgrep

提问by Atif Mohammed Ameenuddin

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

我正在编写一个 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

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`

回答by Moritz Both

The single quotes around $patternin the grep statement make the shell not resolve the shell variable so you should use double quotes.

$patterngrep 语句中的单引号使 shell 无法解析 shell 变量,因此您应该使用双引号。

回答by Paused until further notice.

Only one of those semicolons is necessary (the one before then), but I usually omit it and put thenon a line by itself. You should put double quotes around the variable that you're echoing and around the variable holding your greppattern. Variables that hold filenames should be quoted, also. You can have readdisplay your prompt. You should use $()instead of backticks.

这些分号中只有一个是必需的(之前的那个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

回答by user8952030

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