Getting numbers from a string with grep

11,306
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]'
Share:
11,306
Ghost
Author by

Ghost

Geologist and Engineer. Currently working in AI & Machine Learning for Geochemistry and Geotechniques.

Updated on June 19, 2022

Comments

  • Ghost
    Ghost almost 2 years

    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?

  • Ghost
    Ghost over 10 years
    Doesn't work... it outputs nothing, i also tried ur example and nothing too.
  • Ghost
    Ghost over 10 years
    Did that, and the output is nothing, also tested the examples as i said and same result
  • perreal
    perreal over 10 years
    the code works on ideone, and it works on my box. If it doesn't produce any output on your side then you might have some slightly different input. Can you post what you have tried?