Tutorial :Regular expression in BASH



Question:

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 =/


Solution:1

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  


Solution:2

You can use:

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

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


Solution:3

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>  


Solution:4

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  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »