Sunday, 16 April 2017

Use of Regular Expression

Regular Expression: String which contain wild card character known as regular expression or pattern.

Regular Expression or pattern divided into three types:
i)Character pattern: It is a default pattern
ii)Word pattern
iii)Line pattern

i)Character pattern:
a)Ex: $grep "ind*" demo

b)Ex: $grep "d[aeiou]" sample

c)Ex: $grep "d..l" sample
Note:.is a wild card character,it matches any single character.

ii)Word pattern:
\< \> : Word boundary
\< : Start of the word
\> : End of the word
a)Ex: $grep "\<india\>" demo

b)Ex: $grep "\<india" demo

c)Ex: $grep "india\>" demo

d)Ex : $grep "<\[0-9][0-9][0-9][0-9]\>" num

iii)Line pattern :
^ : Start of line
$ : End of line
a)Ex : $grep "^i" demo
It displays the lines starting with i.

b)Ex : $grep "^Re" departments
It displays the lines starting with Re.

c)Ex : $grep "^\<the\>" file
It displays the lines starting with the.

d)Ex : $grep "^[AIR]" departments
It display lines starting with A,I,R.

e)Ex : $grep "^[^AIR]" departments
It display lines not starting with A,I,R.

f)Ex : $grep "s$" departments
It display lines ending with s.

g)Ex : $grep "[0-9]$" alpha
It display lines ending with number.

h)Ex : $grep "^linux$" subject
It display lines containing linux.

i)Ex : grep ^...$ alpha
It display lines having exactly 3 character.

j)Ex : grep "^\." subject
It displays the line starting with . character.

k)Ex : grep "%\$" alpha
It displays line ending with % character.

l)Ex : grep "^$" alpha
It displays empty lines.


m)Ex : grep -c "^$" alpha
It counts number of empty lines.

n)Ex : grep -n "^$" alpha
It displays empty lines with line number.

o)Deleting empty lines from a file
Ex : $grep -v "^$" subject>output
Here output is an empty file.
Now output file contains all the non empty lines from subject file.