Wednesday 24 April 2013

Regular Expressions in Linux Explained with Examples-II

Interval Regular expressions

These are used to mention no of character/character set reputation info. Note that interval regular expression and extended reg require -E option with grep

Note: In order to use this set of regular expressions you have to us -E with grep command and -r option with sed commands

{n} –n occurrence of previous character
{n,m} – n to m times occurrence of previous character
{m, } –m or more occurrence of previous character.

Example 1: Find all the file names which contain “t” and  t repeats for 3 times consecutively.
ls -l | grep -E ‘t{3}’

-E option is used to extend regexp understanding for grep.

Example 2: Find all the file names which contain l letter in filename with 1 occurrence to 3 occurrence consecutively.

ls -l | grep -E ‘l{1,3}’

Example 3: Find all the file names which contains k letter 5 and more in a file name.

ls -l | grep -E 'k{5,}'
This is bit tricky, let me explain this. Actually we given a range i.e 5 to infinity(Just given only comma after 5).

Extended regular expressions

These regular expressions extend the regular expression features.

Note:In order to use this set of regular expressions you have to us -E with grep command and -r option with sed commands

+ –one more occurrence of previous character
| — or option, we can specify either a character to present in the pattern.
? — 0 or one occurrence of previous character
() — grouping of character set.

Example 1: Find all the files which contains f letter, one more occurrences.

ls -l | grep -E ‘f+’

Example 2: Find all the files which may contain a or b in its file name

ls -l | grep -E ‘a|b’

Example 3: Find all the files which may contain t or 1 occurrence of t in filename
ls -l | grep -E ‘t?’

for example i have below files
test
best
see
do

my grep command will list test, best files as output.

Note: My grep output contain all these files though see and do files do not contain t, the is because we given ? which will search for 0 or 1 occurrence of previous character. See and do contains 0 t’s in its name, so it will find these files too.

Example 4: Find all the files which contains ab in the sequence
ls -l | grep -E ‘(ab)’

This will give all the files which contains ab in the file name consequently.

Please stay tuned to our next article on grep command and how to use it.

0 blogger-disqus:

Post a Comment