tags:

views:

313

answers:

4

Hello everyone, I was hoping someone could answer my quick question as I am going nuts!

I have recently started learning regular expressions in my Java programming however am a little confused how to get certain features to work correctly directly in BASH. For example, the following code is not working as I think it should.

echo 2222 | grep '2\{2\}'

I am expecting it to return:

22

I have tried variations of it including:

echo 2222 | grep '2{2}'
echo 2222 | grep -P '2\{2\}'
echo 2222 | grep -E '2\{2\}'

However I am completely out of ideas. I'm sure this is a simple parameter / syntax fix and would love some help! P.S I've done tons of googling and every reference I find does not work in BASH; regex's can run on so many different platforms and engines =/

+3  A: 

You can use:

echo 2222 | grep -o '2\{2\}'

except that it will show the output twice, since it matches twice on that line.

Ignacio Vazquez-Abrams
+1  A: 

you didn't try

echo 2222 | grep -E '2{2}'

that'll return 2222 that is to say "it's matching your line"

sed may help you to visualize your regexp

echo 22 33 342 22 | sed  's/2\{2\}/<match>/g'

returns for instance

<match> 33 342 <match>
Darkyo
+6  A: 
echo 2222 | grep -E '2{2}'
2222

The regex will pattern match on the line, and either print out the whole line (2222) if it matches, or nothing if it doesn't.

It will NOT pull out a portion of the output. For that, you want something like sed:

echo 2222 | sed 's/.*\(2\{2\}\).*/\1/'
22
Tim
fyi only, `egrep` is deprecated. use `grep -E` whenever possible
ghostdog74
Thanks ghostdog, I didn't know that. For those curious, it says so in the man page: http://man.he.net/man1/egrep
Tim
+1  A: 

if you just searching for two "2"s at the beginning of string, no need to use external tools

string=2222
case "$string" in
 22*) echo "ok";;
esac
ghostdog74