Monday, 15 August 2011

Regular Expressions In grep

grep PARAMS what? where?

msRoot:~ ioannis$ grep ^paddi* styl*
padding-left: 0;
padding:5px 2px;
padding-left:4px;
padding:3px;
msRoot:~ ioannis$



grep 'word1|word2|word3' /path/to/file

example:
msRoot:~ ioannis$ grep -w 'padding\|margin' *.css
th,td { margin: 0; padding: 0; }
margin-left: 2em;
margin-top: 20px;


use alway .\ escape in .
and \| escape in strings 'padding\|margin'

Use the following syntax:
grep 'word1|word2' filename
How Do I do AND with grep?

Use the following syntax to display all lines that contain both 'word1' and 'word2'
grep 'word1' filenae | grep 'word2'


Match a character "v" two times:
egrep "v{2}" filename


You can use ^ and $ to force a regex to match only at the start or end of a line, respectively. The following example displays lines starting with the vivek only:
grep ^vivek /etc/passwd


Find lines ending with word foo:
grep 'foo$' filename

Match Vivek or vivek:
grep '[vV]ivek' filename

You can match two numeric digits (i.e. match foo11, foo12 etc):
grep 'foo[0-9][0-9]' filename



Escaping the dot

The following regex to find an IP address 192.168.1.254 will not work:
grep '192.168.1.254' /etc/hosts
All three dots need to be escaped:
grep '192\.168\.1\.254' /etc/hosts
The following example will only match an IP address:

egrep '[[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}' filename

The following will match word Linux or UNIX in any case:


http://www.cyberciti.biz/faq/grep-regular-expressions/

No comments:

Post a Comment