bash 如何将grep的输出传递给sed?

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

How to pass output of grep to sed?

bashshellubuntu

提问by batman

I have a command like this :

我有一个这样的命令:

cat error | grep -o [0-9]

which is printing only numbers like 2,30and so on. Now I wish to pass thisnumber to sed.

它只打印数字,如230等等。现在我希望将这个数字传递给sed.

Something like :

就像是 :

cat error | grep -o [0-9] | sed -n '$OutPutFromGrep,$OutPutFromGrepp'

Is it possible to do so?

有可能这样做吗?

I'm new to shell scripting. Thanks in advance

我是 shell 脚本的新手。提前致谢

采纳答案by Thor

If the intention is to print the lines that grepreturns, generating a sedscript might be the way to go:

如果打算打印grep返回的行,则生成sed脚本可能是要走的路:

grep -E -o '[0-9]+' error | sed 's/$/p/' | sed -f - error

回答by themel

You are probably looking for xargs, particularly the -Ioption:

您可能正在寻找xargs,尤其是以下-I选项:

themel@eristoteles:~$ xargs -I FOO echo once FOO, twice FOO
hi
once hi, twice hi
there
once there, twice there

Your example:

你的例子:

themel@eristoteles:~$ cat error
error in line 123
error in line 234
errors in line 345 and 346
themel@eristoteles:~$ grep -o '[0-9]*' < error | xargs -I OutPutFromGrep echo sed -n 'OutPutFromGrep,OutPutFromGrepp'
sed -n 123,123p
sed -n 234,234p
sed -n 345,345p
sed -n 346,346p

For real-world use, you'll probably want to pass sedan input file and remove the echo.

对于实际使用,您可能希望传递sed输入文件并删除echo.

(Fixed your UUOC, by the way. )

(顺便说一下,修复了你的UUOC。)

回答by Ivaylo Strandjev

Yes you can pass output from grep to sed.

是的,您可以将输出从 grep 传递到 sed。

Please note that in order to match whole numbers you need to use [0-9]* not only [0-9] which would match only a single digit.

请注意,为了匹配整数,您需要使用 [0-9]* 而不仅仅是 [0-9],后者只能匹配一位数字。

Also note you should use double quotes to get variables expanded(in the sed argument) and it seems you have a typo in the second variable name.

另请注意,您应该使用双引号来扩展变量(在 sed 参数中),而且您似乎在第二个变量名称中有拼写错误。

Hope this helps.

希望这可以帮助。