grep for an alphanumeric strings of any length with a colon on each side
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
Admin
Updated on September 18, 2022Comments
-
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 over 10 yearsYou just need to enable the extended regex capabilities of
grep
by including the-E
switch.
-
-
Admin over 10 yearsthanks! 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 over 10 years@TorThommesen - you can edit the title of your Q if it's not correct.
-
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).