为什么这个“grep -o”会失败,我该如何应对呢?

时间:2022-01-14 08:53:48

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 -o in 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在这里失败的原因是否有一些解释,或者只是一个bug?我以这种方式在bash脚本中使用grep -o,我希望可以在不同的计算机上运行该脚本(可能有不同版本的grep)。是否有一种“正确的方式”来获得一致的行为?

5 个解决方案

#1


9  

Yes, 2.5.1's -o handling was buggy: http://www.mail-archive.com/bug-grep@gnu.org/msg00993.html

是的,2.5.1的-o处理是错误的:http://www.mail-archive.com/bug-grep@gnu.org/msg00993.html

Grep is probably not the right tool for this; sed or tr or even perl might be better depending on what the actual task is.

Grep可能不是合适的工具;sed或tr甚至perl可能更好地取决于实际的任务是什么。

#2


2  

you can use the shell. its faster

你可以用壳层。它的速度

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

#3


2  

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

我遇到了同样的问题,发现那台机器上安装了白鹭。一个快速的解决方案正在使用

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

#4


0  

This will give similar results:

这将产生类似的结果:

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

Your question is a near-duplicate of this one.

你的问题几乎是这个问题的翻版。

#5


-1  

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

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

  1. grep -E
  2. grep - e
  3. egrep (like Sebastian posted).
  4. egrep(如塞巴斯蒂安发布)。

Good luck!

好运!

#1


9  

Yes, 2.5.1's -o handling was buggy: http://www.mail-archive.com/bug-grep@gnu.org/msg00993.html

是的,2.5.1的-o处理是错误的:http://www.mail-archive.com/bug-grep@gnu.org/msg00993.html

Grep is probably not the right tool for this; sed or tr or even perl might be better depending on what the actual task is.

Grep可能不是合适的工具;sed或tr甚至perl可能更好地取决于实际的任务是什么。

#2


2  

you can use the shell. its faster

你可以用壳层。它的速度

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

#3


2  

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

我遇到了同样的问题,发现那台机器上安装了白鹭。一个快速的解决方案正在使用

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

#4


0  

This will give similar results:

这将产生类似的结果:

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

Your question is a near-duplicate of this one.

你的问题几乎是这个问题的翻版。

#5


-1  

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

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

  1. grep -E
  2. grep - e
  3. egrep (like Sebastian posted).
  4. egrep(如塞巴斯蒂安发布)。

Good luck!

好运!