bash 如何将shell脚本参数作为执行grep命令时使用的变量传递

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26326156/
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-18 11:32:31  来源:igfitidea点击:

How to pass a shell script argument as a variable to be used when executing grep command

bashshellgrep

提问by Donnoughue

I have a file called fruit.txt which contains a list of fruit names (apple, banana.orange,kiwi etc). I want to create a script that allows me to pass an argument when calling the script i.e. script.sh orange which will then search the file fruit.txt for the variable (orange) using grep. I have the following script...

我有一个名为fruit.txt 的文件,其中包含一个水果名称列表(苹果、banana.orange、kiwi 等)。我想创建一个脚本,它允许我在调用脚本时传递一个参数,即 script.sh orange 它将使用 grep 在文件fruit.txt 中搜索变量(orange)。我有以下脚本...

script name and argument as follows: script.sh orange

脚本名称和参数如下:script.sh orange

script snippet as follows:

脚本片段如下:

#!/bin/bash
nameFind=
echo `cat` "fruit.txt"|`grep` | $nameFind 

But I get the grep info usage command and it seems that the script is awaiting some additional command etc. Advice greatly appreciated.

但是我得到了 grep info 使用命令,并且脚本似乎正在等待一些额外的命令等。非常感谢您的建议。

回答by Tom Fenech

Something like this should work:

这样的事情应该工作:

#!/bin/bash

name=""
grep "$name" fruit.txt

There's no need to use catand greptogether; you can simply pass the name of the file as the third argument, after the pattern to be matched. If you want to match fixed strings (i.e. no regular expressions), you can also use the -Fmodifier:

不需要cat和和grep一起使用;您可以在要匹配的模式之后简单地将文件名作为第三个参数传递。如果要匹配固定字符串(即没有正则表达式),还可以使用-F修饰符:

grep -F "$name" fruit.txt

回答by dramzy

The piping syntax is incorrect there. You are piping the output of grep as input to the variable named nameFind. So when the grep command tries to execute it is only getting the contents of fruit.txt. Do this instead:

那里的管道语法不正确。您正在将 grep 的输出作为输入传递给名为 nameFind 的变量。因此,当 grep 命令尝试执行时,它只会获取fruit.txt 的内容。改为这样做:

#!/bin/bash
nameFind=
grep "$nameFind" fruit.txt