4 ms·
Jeeeeesus christ, that grep is ugly. grep "[0-9]\{3\}[-]\?[0-9]\{3\}[-]\?[0-9]\{4\}" filename.txt The default behavior of grep appears to be to not treat {}
by waterhouse 15y ago
Jeeeeesus christ, that grep is ugly.
grep "[0-9]\{3\}[-]\?[0-9]\{3\}[-]\?[0-9]\{4\}" filename.txt
The default behavior of grep appears to be to not treat {}?() as special characters. Which is generally boneheaded in my experience, and certainly in this case. An irritated man will use egrep--short for grep -E, "extended regexes"--i.e. sane regexes:
egrep "[0-9]{3}-?[0-9]{3}-?[0-9]{4}" filename.txt
This is just a direct translation. If I wrote the regex myself, I would probably also recognize spaces as delimiters (as in "999 999 9999"), and maybe note that the area code might be missing or have parens around it, etc.--depending on just what I was trying to parse. I dunno, maybe he's parsing regular machine output and his original regex would suffice, so I won't go farther than an equivalent translation. But I will, for kicks, mention this:
egrep "([0-9]{3}-?){2}[0-9]{4}" filename.txt
(Note that - is not a special character in either grep or egrep, although command-line programs in general treat specially any argument beginning with -, so it is a good idea to use [-] instead of - if that happens to be the first character of your string. But after that, no.)
Also, for general purposes, grep -P (Perl regexes) is best of all, because it can do *? non-greedy matching. A really irritated man has aliased pgrep to "grep -P --color=auto" in his bash startup file, and has also (perhaps dangerously) aliased grep to it as well. (That breaks fewer things than altering GREP_OPTIONS.)