2014年5月21日 星期三

[Linux] Line and word anchors by using grep tool


[Linux] Line and word anchors by using grep tool

 



The ^ anchor specifies that the pattern following it should be at the start of the line:













[manish@clone ~]$ grep '^th' testfile


this






The $ anchor specifies that the pattern before it should be at the end of the line.













[manish@clone ~]$ grep 'i$' testfile


Hi






The operator \< anchors the pattern to the start of a word.













[manish@clone ~]$ grep '\<fe' testfile


to carry out few regular expressions






Similarly, \> anchors the pattern to the end of a word.













[manish@clone ~]$ grep 'le\>' testfile


is test file






The \b (word boundary) anchor can be used in place of \< and \> to signify the beginning or end of a word:













[manish@clone ~]$ grep -e '\breg' testfile


to carry out few regular expressions






Finally, we look at the | (alternation) operator, which is part of the extended regex features. A pattern containing this operator separately matches the parts on either side of it; if either one is found, the line containing it is a match. The parts can themselves be complex regular expressions, so this means you can check each line in a file for multiple search patterns in one pass.













[manish@clone ~]$ grep -E 'hi|bc' testfile


this


Abcd






That was pretty simple; so let’s try a more complicated one. Can you reason out why the output lines for this regex are as shown below?




[manish@clone ~]$ grep -E '^[t-z]+|[^a-z]+$' testfile


this


to carry out few regular expressions


123 456


ABCD

 



Reference :



Related Posts:

0 意見:

張貼留言