Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I have the following regular expression:

([:digit:]{4})-([:digit:]{1,2})-([:digit:]{1,2})

It should get dates in this format:

2010-12-19

And I am using it on filenames that look like this:

2010-12-19-xxx-xxx-xxx.markdown

And, when I use it with grep like this:

echo $POST | grep -oE "([:digit:]{4})-([:digit:]{1,2})-([:digit:]{1,2})" # $POST is the filename

It doesn't work, I just get emptiness.

share|improve this question

3 Answers 3

up vote 4 down vote accepted

Try this:-

echo $POST | grep -oE "[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}"

If I try it here, I get:-

[andys@daedalus ~]$ echo "2010-12-19-aaa-bbb-ccc-ddd.markdown" | grep -oE "[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}"
2010-12-19

Hope that's what you're looking for.

share|improve this answer
    
Awesome, that worked like a charm. Thanks! –  Wuffers Dec 20 '10 at 1:10
    
No problem! :-) –  Andy Smith Dec 20 '10 at 1:11

You don't need the parentheses, but you do need more square brackets. Character classes have the same characteristics as individual characters. Just as you might search for vowels like this: [aeiou], or digits like this: [0123456789] or this: [0-9], you need to enclose a class such as [:digit:] or [:upper:] in a bracket expression as well: [[:xdigit:]] (hex digits).

grep -oE "[[:digit:]]{4}-[[:digit:]]{1,2}-[[:digit:]]{1,2}"
share|improve this answer

Andy's answer is fine, but if you want something closer to your original syntax, you could try:

echo $POST | egrep -oE "([[:digit:]]{4})-([[:digit:]]{1,2})-([[:digit:]]{1,2})"

You need egrep here for extended regular expressions, and the double brackets for character classes.

share|improve this answer
1  
Actually, you don't need egrep if you have the -E option. From the grep man page: "Egrep is the same as grep -E" –  Wuffers Dec 20 '10 at 1:45

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.