bash 为什么这个 `grep -o` 会失败,我应该如何解决它?

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

Why does this `grep -o` fail, and how should I work around it?

regexbashgrep

提问by Anton Geraschenko

Given the input

鉴于输入

echo abc123def | grep -o '[0-9]*'

On one computer (with GNU grep 2.5.4), this returns 123, and on another (with GNU grep 2.5.1) it returns the empty string. Is there some explanation for why grep 2.5.1 fails here, or is it just a bug? I'm using grep -oin this way in a bash script that I'd like to be able to run on different computers (which may have different versions of grep). Is there a "right way" to get consistent behavior?

在一台计算机上(使用 GNU grep 2.5.4),它返回123,而在另一台计算机上(使用 GNU grep 2.5.1)它返回空字符串。是否有一些解释为什么 grep 2.5.1 在这里失败,或者它只是一个错误?我grep -o在 bash 脚本中以这种方式使用,我希望能够在不同的计算机上运行(可能有不同版本的 grep)。是否有“正确的方法”来获得一致的行为?

采纳答案by Grandpa

Yes, 2.5.1's -ohandling was buggy: http://www.mail-archive.com/[email protected]/msg00993.html

是的,2.5.1 的-o处理有问题:http: //www.mail-archive.com/[email protected]/msg00993.html

Grep is probably not the right tool for this; sedor tror even perlmight be better depending on what the actual task is.

Grep 可能不是用于此的正确工具;sed或者tr甚至perl可能更好,具体取决于实际任务是什么。

回答by ghostdog74

you can use the shell. its faster

你可以使用外壳。它更快

$ str=abc123def
$ echo ${str//[a-z]/}
123

回答by Sebastian

I had the same issue and found that egrepwas installed on that machine. A quick solution was using

我有同样的问题,发现egrep那台机器上安装了它。一个快速的解决方案是使用

 echo abc123def | egrep -o '[0-9]*'

回答by Paused until further notice.

This will give similar results:

这将给出类似的结果:

echo abc123def | sed -n 's/[^0-9]*\([0-9]\+\).*//p'

Your question is a near-duplicate of this one.

你的问题几乎是这个问题的重复。

回答by Robert

Because you are using a regex so you must use either:

因为您使用的是正则表达式,所以您必须使用:

  1. grep -E
  2. egrep (like Sebastian posted).
  1. grep -E
  2. egrep(就像塞巴斯蒂安发布的那样)。

Good luck!

祝你好运!