Ghost
Ghost

Reputation: 1523

Getting numbers from a string with grep

I came with another simple question...

I got a string with a substring in the format xx:xx:xx where the x's are numbers. I want to extract that substring including the ":" symbol, so my output would be "xx:xx:xx".

I think it can be done with a grep -Eo [0-9], but im not sure of the syntax... Any help?

Upvotes: 4

Views: 12445

Answers (1)

perreal
perreal

Reputation: 97918

echo "substring in the format 12:43:37 where the x's are numbers" | 
      grep -o '[0-9:]*'

Output:

12:43:37

If you have other numbers in the input string you can be more specific:

grep -o '[0-9]*:[0-9]*:[0-9]*'

even:

grep -o '[0-9][0-9]:[0-9][0-9]:[0-9][0-9]'

Upvotes: 7

Related Questions