9

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?

Anton Geraschenko
  • 1,409
  • 2
  • 11
  • 20
  • 1
    Why would you want to grep on a regex that can match zero characters, anyway? I would expect it to match every line, not just lines with digits in them. – Alan Moore Nov 15 '09 at 03:58

5 Answers5

9

Yes, 2.5.1's -o handling was buggy: 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.

Grandpa
  • 3,053
  • 1
  • 25
  • 35
  • +1: But if there's variation between minor GNU `grep` versions (albeit due to bugs) there's not much chance of finding consistency between different computers. There are plenty of other tools, though. – pavium Nov 15 '09 at 03:51
  • 1
    Recommending to use an other tool, without a correct solution is not a good answer. As an evidence, in most of the cases it can be solved with the usage of pure bash. You did not include an exact solution for me. – kisp Aug 23 '13 at 21:32
2

you can use the shell. its faster

$ str=abc123def
$ echo ${str//[a-z]/}
123
ghostdog74
  • 327,991
  • 56
  • 259
  • 343
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]*'
Sebastian
  • 1,408
  • 1
  • 20
  • 28
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.

Community
  • 1
  • 1
Dennis Williamson
  • 346,391
  • 90
  • 374
  • 439
-1

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

  1. grep -E
  2. egrep (like Sebastian posted).

Good luck!

Robert
  • 1
  • 2
    -E/egrep is required for *extended* regular expressions; '[0-9]*' is a valid basic regular expression. (The 're' in 'grep' stands for regular expression). Perhaps the bug in 2.5.1 was not present in the extended regular expression support, but the mere fact that a regular expression is used does not mean you need -E. – chepner Jul 27 '12 at 23:53