How would you grep for an alphanumeric strings of 1 to 50 characters (ideally, any length would work too) with a colon on each side – a typical result would be all the lines containing the string :shopping:. So far I've got the code below (I've tried some variations on it) which doesn't work:

grep ':[[:alnum:]]{1,100}:' ~/x.txt
  • You just need to enable the extended regex capabilities of grep by including the -E switch. – slm Sep 7 '13 at 21:41

You need to enable extended regular expressions for this:

grep -E ':[[:alnum:]]+:' ~/x.txt

With basic regular expressions, you can write it like:

grep ':[[:alnum:]]\{1,100\}:' ~/x.txt

Note that \{ (as opposed to \+ or \? for instance) is standard and portable, and actually the BRE equivalents of + and ? are typically written with \{: \{1,\} and \{0,1\}. grep -E is also standard and portable though, so you might as well use it as it makes for more readable regexps in those cases.


You are using a extended regular expresion so you need to use the -E option:

grep -E ':[[:alnum:]]{1,100}:' ~/x.txt
  • thanks! I put the other answer as correct because I did not write up my "ideal" script in the headline, and I don't want to cause people who google for an answer to copy paste the wrong answer, but I'll use yours. :) – user36719 Sep 7 '13 at 21:42
  • 1
    @TorThommesen - you can edit the title of your Q if it's not correct. – slm Sep 7 '13 at 23:08

Since no one else mentioned it, you may also use egrep, which, as I understand it, is equivalent to grep -E.

  • 1
    egrep was the historical command to grep with EREs. The functionality of grep and egrep have since (a long ago) been merged into grep with the -E option. egrep is now considered obsolete/deprecated (but unlikely to go as some people are still used to it). – Stéphane Chazelas Nov 19 '15 at 14:27

Your Answer
