How to grep lines, based on a certain pattern?

Solution 1:

The simplest way would be to add a space after your pattern:

$ grep '/aa/bbbb/cccccc ' file
2014-05-05      09:11:53    /aa/bbbb/cccccc             29899

Or, to match all kinds of whitespace:

$ grep  '/aa/bbbb/cccccc[[:space:]]' file
2014-05-05      09:11:53    /aa/bbbb/cccccc             29899

Or

$ grep -P '/aa/bbbb/cccccc\s+' file
2014-05-05      09:11:53    /aa/bbbb/cccccc             29899

Or, with a positive lookahead:

$ grep -P '/aa/bbbb/cccccc(?=\s)' file
2014-05-05      09:11:53    /aa/bbbb/cccccc             29899

Or, with a negative lookahead:

$ grep -P '/aa/bbbb/cccccc(?!\S)' file
2014-05-05      09:11:53    /aa/bbbb/cccccc             29899

Or you can reverse the match:

$ grep  -v 'c?' file
2014-05-05      09:11:53    /aa/bbbb/cccccc             29899

Or, to also match lines that contain nothing but your pattern (no trailing whitespace):

grep -P '/aa/bbbb/cccccc(\s+|$)' file 
grep -E '/aa/bbbb/cccccc(\s+|$)' file 

Or, you can just use a small script:

  • In awk:

    $ awk '$3=="/aa/bbbb/cccccc"' file
    2014-05-05      09:11:53    /aa/bbbb/cccccc             29899
    

    Or, if you don't know which field your pattern is in

    $ awk '{for(i=1;i<=NF;i++){if($i=="/aa/bbbb/cccccc"){print}}}' file
    2014-05-05      09:11:53    /aa/bbbb/cccccc             29899
    
  • In Perl

    $ perl -ane 'print if grep {$_ eq "/aa/bbbb/cccccc"} @F' file
    2014-05-05      09:11:53    /aa/bbbb/cccccc             29899
    

Solution 2:

Try the below grep command which uses -P (Perl-regexp) parameter.

grep -P '(?<!\S)/aa/bbbb/cccccc(?!\S)' file
  • (?<!\S) This negative lookbehind asserts that the character which preceeds the string /aa/bbbb/cccccc would be any but not a non-space character.

  • (?!\S) Negative lookahead asserts that the character following the match would be any but not a non-space character.

Another grep,

 grep -E '(^|\s)/aa/bbbb/cccccc(\s|$)' file

Through python,

script.py

#!/usr/bin/python3
import re
import sys
file = sys.argv[1]
with open(file, 'r') as f:
    for line in f:
        for i in line.split():
            if i == "/aa/bbbb/cccccc":
                print(line, end='')

Save the above code in a file and name it as script.py. Then execute the above script by

python3 script.py /path/to/the/file/you/want/to/work/with

Solution 3:

To complement @AvinashRaj's answer, you can use also command like this.

grep -P '/a+/b+/c+(?!\S)' file