grep for an alphanumeric strings of any length with a colon on each side

39,580

Solution 1

You need to enable extended regular expressions for this:

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

Solution 2

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.

Solution 3

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

grep -E ':[[:alnum:]]{1,100}:' ~/x.txt
Share:
39,580
Admin
Author by

Admin

Updated on September 18, 2022

Comments

  • Admin
    Admin over 1 year

    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
    
    • slm
      slm over 10 years
      You just need to enable the extended regex capabilities of grep by including the -E switch.
  • Admin
    Admin over 10 years
    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. :)
  • slm
    slm over 10 years
    @TorThommesen - you can edit the title of your Q if it's not correct.
  • Stéphane Chazelas
    Stéphane Chazelas over 8 years
    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).