Grep: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
No edit summary
Line 24: Line 24:
=Regular Expressions=
=Regular Expressions=


<pre>
{{Internal|grep Regular Expressions|grep Regular Expressions}}
^ - beginning of line
 
$ - end of line
 
\t - tab
 
digits: [0-9]* \d*
 
\. dot
</pre>
 
Characters that need and do not need escaping:
 
<blockquote style="background-color: #f9f9f9; border: solid thin lightgrey;">
:[[Sed_Regular_Expressions#Special_Characters_.28need_to_be_escaped_in_regular_expressions.29|sed: Special Characters (need to be escaped in regular expressions)]]
 
:[[Sed_Regular_Expressions#Non-Special_Characters_.28do_not_need_to_be_escaped_in_regular_expressions.29|sed: Non-Special Characters (do not need escaping in regular expressions)]]
</blockquote>


=Recipes=
=Recipes=

Revision as of 20:53, 29 July 2017

Internal

Overview

grep accepts regular expressions. Both " " and ' ' can be used to enclose the expression to search for.

If the expression is found, the enclosing lines are sent to stdout the command returns 0 (success).

If the expression is NOT found, the command returns 1 (failure).


    if grep -q "some regex" ./file.txt; then
        # do something if expression is found
    else
        # do something else if the expression is not found
    fi

Regular Expressions

grep Regular Expressions

Recipes

Including TWO expressions at the same time

cat /proc/cpuinfo | grep 'processor\|siblings'

processor	: 0
siblings	: 2
processor	: 1
siblings	: 2

The method works even if there are spaces and other regular expression characters within the alternative regexes:

... | grep ' logger: [1-9]\+\.\|(concurrent mode failure)'

This will select either "logger: [1-9]\+\." or "(concurrent mode failure)"

Excluding TWO expressions at the same time

     echo "something" | grep -v "blah" | grep -v "blah2"

Do not Send Anything to stout

... and avoid > /dev/null:

    grep -q

--color

grep --color 'context.layer='

Prefix the Line with the "Line Number" (-n)

-n prefixes the line with the line number.

sed: Insert a Line/Append in a Specific Position (line number) in a file

Return Only the First Match

-m means "stop reading the file about num matches. So to return the first match:

-m 1