Linux‎ > ‎

grep using examples

Thank you for visiting this page, this page has been update in another link Grep using examples on Linux
Grep is one of the most commonly used tool on linux, hardly know that someone on linux seldom use it. But, not most of people use it in advanced ways.
Let's get started.
       grep  searches  the named input FILEs (or standard input if no files are named, or if a single hyphen-minus (-) is given as file name) for lines containing a match to the given PATTERN.  By default, grep prints the matching lines.

       In addition, two variant programs egrep and fgrep are available.  egrep is the same as grep -E.  fgrep is the same as grep -F.  Direct invocation  as  either  egrep  or  fgrep  is  deprecated,  but  is  provided to allow historical applications that rely on them to run unmodified.
Here are examples for the description
grep 'word' filename grep 'word' file1 file2 file3 grep 'string1 string2' filename cat otherfile | grep 'something' command | grep 'something' command option1 | grep 'data
grep --color bnx2 /var/log/dmesg
bnx2: Broadcom NexXtreme II Gigabit Ethernet Driver bnx2 v2.2.3
grep aaa -
aaa
aaa
bbb
ccc
Note: the second aaa is the output of grep

Example #1
-n, --line-number
Prefix each line of output with the 1-based line number within its input file. (-n is specified by POSIX.)

$ grep -n bnx2 /var/log/dmesg
1128:bnx2: Broadcom NetXtreme II Gigabit Ethernet Driver bnx2 v2.2.3 (June 27, 2012)
1129:bnx2 0000:03:00.0: PCI INT A -> GSI 16 (level, low) -> IRQ 16
1130:bnx2 0000:03:00.0: firmware: requesting bnx2/bnx2-mips-06-6.2.3.fw
Exampel #2
       -v, --invert-match
              Invert the sense of matching, to select non-matching lines.  (-v is specified by POSIX.)
$ grep -v bash /etc/passwd
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
...

Example #3
       -c, --count
              Suppress normal output; instead print a count of matching lines for each input file.  With the -v, --invert-match  option  (see
              below), count non-matching lines.  (-c is specified by POSIX.)
$ grep -c bash /etc/passwd
17

Example #4
       -i, --ignore-case
              Ignore case distinctions in both the PATTERN and the input files.  (-i is specified by POSIX.)
$grep -i pci /var/log/dmsg
...
[drm] PCI GART of 512M enabled (table at 0x0000000037880000).
input: Avocent IBM 73P5832 as /devices/pci0000:00/0000:00:1d.0/usb2/2-1/2-1:1.0/input/input2
input: Avocent IBM 73P5832 as /devices/pci0000:00/0000:00:1d.0/usb2/2-1/2-1:1.1/input/input3
...

Example #5
       -w, --word-regexp
              Select only those lines containing matches that form whole words.  The test is that the matching substring must  either  be  at
              the  beginning  of  the  line, or preceded by a non-word constituent character.  Similarly, it must be either at the end of the
              line or followed by a non-word constituent character.  Word-constituent characters are letters, digits, and the underscore.
$ grep -w bnx /var/log/dmesg
$ grep -w bnx2 /var/log/dmesg
bnx2: Broadcom NetXtreme II Gigabit Ethernet Driver bnx2 v2.2.3 (June 27, 2012)
bnx2 0000:03:00.0: PCI INT A -> GSI 16 (level, low) -> IRQ 16
bnx2 0000:03:00.0: firmware: requesting bnx2/bnx2-mips-06-6.2.3.fw
bnx2 0000:03:00.0: firmware: requesting bnx2/bnx2-rv2p-06-6.0.15.fw

Example #6
       -x, --line-regexp
              Select only those matches that exactly match the whole line.  (-x is specified by POSIX.)
$ grep -x bnx2 /var/log/dmesg
$ grep -x "bnx2 0000:03:00.0: PCI INT A -> GSI 16 (level, low) -> IRQ 16" /var/log/dmesg
bnx2 0000:03:00.0: PCI INT A -> GSI 16 (level, low) -> IRQ 16

Example #7
       -L, --files-without-match
              Suppress normal output; instead print the name of each input file from which no output would normally have been  printed.   The
              scanning will stop on the first match.

       -l, --files-with-matches
              Suppress  normal  output;  instead  print  the name of each input file from which output would normally have been printed.  The
              scanning will stop on the first match.  (-l is specified by POSIX.)

$ grep -l bnx /var/log/dmesg /var/log/messages
/var/log/dmesg
$ grep -L bnx /var/log/dmesg /var/log/messages
/var/log/messages

Example #8
       -R, -r, --recursive
              Read all files under each directory, recursively; this is equivalent to the -d recurse option.
       -D ACTION, --devices=ACTION
              If  an  input file is a device, FIFO or socket, use ACTION to process it.  By default, ACTION is read, which means that devices
              are read just as if they were ordinary files.  If ACTION is skip, devices are silently skipped.
$grep -r mtx tape | more
tape/mtx-1.2.18rel/mam2debug2.c:#include "mtx.h"
tape/mtx-1.2.18rel/mam2debug2.c:#include "mtxl.h"
tape/mtx-1.2.18rel/mtxl.README.html:[Also see the SourceForge <a href="http://sourceforge.net/projects/mtx">
tape/mtx-1.2.18rel/mtxl.README.html:<i>mtx</i> is a set of low level driver programs to control features
tape/mtx-1.2.18rel/mtxl.README.html:1988). <i>mtx</i> is designed to be a low level driver in a larger
tape/mtx-1.2.18rel/mtxl.README.html:<i>mtx</i> is not
...

Example #9, print 2 lines before and after matched line

       -A NUM, --after-context=NUM
              Print  NUM  lines of trailing context after matching lines.  Places a line containing a group separator (--) between contiguous
              groups of matches.  With the -o or --only-matching option, this has no effect and a warning is given.

       -B NUM, --before-context=NUM
              Print NUM lines of leading context before matching lines.  Places a line containing a group separator (--)  between  contiguous
              groups of matches.  With the -o or --only-matching option, this has no effect and a warning is given.

       -C NUM, -NUM, --context=NUM
              Print NUM lines of output context.  Places a line containing a group separator (--) between contiguous groups of matches.  With
              the -o or --only-matching option, this has no effect and a warning is given.

$ grep --color -A 2 -B 2  "command line" /var/log/dmesg
Built 1 zonelists in Zone order, mobility grouping on.  Total pages: 4133096
Policy zone: Normal
Kernel command line: ro root=UUID=8e37d096-4494-4a31-80df-e74b6a8c26e3 rd_NO_LUKS rd_NO_LVM LANG=en_US.UTF-8 rd_NO_MD quiet SYSFONT=latarcyrheb-sun16  crashkernel=130M@0M  KEYBOARDTYPE=pc KEYTABLE=us rd_NO_DM
PID hash table entries: 4096 (order: 3, 32768 bytes)
Checking aperture...

$ grep --color -C 2 "command line" /var/log/dmesg
Built 1 zonelists in Zone order, mobility grouping on.  Total pages: 4133096
Policy zone: Normal
Kernel command line: ro root=UUID=8e37d096-4494-4a31-80df-e74b6a8c26e3 rd_NO_LUKS rd_NO_LVM LANG=en_US.UTF-8 rd_NO_MD quiet SYSFONT=latarcyrheb-sun16  crashkernel=130M@0M  KEYBOARDTYPE=pc KEYTABLE=us rd_NO_DM
PID hash table entries: 4096 (order: 3, 32768 bytes)
Checking aperture...

Match regular expression in files

Example #10

$grep ^root /etc/passwd
root:x:0:0:root:/root:/bin/bash

Example #11, remove empty lines

$grep -v ^$ README.rst
===========
 PgFincore
===========
--------------------------------------------------------------
 A set of functions to manage pages in memory from PostgreSQL
--------------------------------------------------------------
A set of functions to handle low-level management of relations using mincore to
explore cache memory.

Example #12

grep -w -E 'bnx|pci' /var/log/dmsg

...

pci 0000:00:1f.0: rerouting interrupts for [8086:2670]
pci 0000:01:06.0: Boot video device
bnx2: Broadcom NetXtreme II Gigabit Ethernet Driver bnx2 v2.2.3 (June 27, 2012)
bnx2 0000:03:00.0: PCI INT A -> GSI 16 (level, low) -> IRQ 16


Example #13

$ grep "0000\:00\:0[1-9]" /var/log/dmesg

pci 0000:00:02.0: PME# supported from D0 D3hot D3cold
pci 0000:00:02.0: PME# disabled
pci 0000:00:03.0: PME# supported from D0 D3hot D3cold
pci 0000:00:03.0: PME# disabled
pci 0000:00:04.0: PME# supported from D0 D3hot D3cold
pci 0000:00:04.0: PME# disabled


Example #14

$ grep -w -e "pcieport" -e "bnx2" /var/log/dmesg
pcieport 0000:00:1c.0: setting latency timer to 64
pcieport 0000:00:1c.0: irq 24 for MSI/MSI-X
pcieport 0000:00:1c.1: setting latency timer to 64
pcieport 0000:00:1c.1: irq 25 for MSI/MSI-X
bnx2: Broadcom NetXtreme II Gigabit Ethernet Driver bnx2 v2.2.3 (June 27, 2012)
bnx2 0000:03:00.0: PCI INT A -> GSI 16 (level, low) -> IRQ 16
bnx2 0000:03:00.0: firmware: requesting bnx2/bnx2-mips-06-6.2.3.fw
bnx2 0000:03:00.0: firmware: requesting bnx2/bnx2-rv2p-06-6.0.15.fw
bnx2 0000:03:00.0: eth0: Broadcom NetXtreme II BCM5708 1000Base-T (B2) PCI-X 64-bit 133MHz found at mem ce000000, IRQ 16, node addr 00:1a:64:63:3f:00
bnx2 0000:06:00.0: PCI INT A -> GSI 17 (level, low) -> IRQ 17

REGULAR EXPRESSIONS

       A  regular  expression  is  a  pattern that describes a set of strings.  Regular expressions are constructed analogously to arithmetic expressions, by using various operators to combine smaller expressions.

       grep understands three different versions of regular expression syntax: “basic,” “extended” and  “perl.”  In  GNU grep,  there  is  no difference  in  available  functionality between basic and extended syntaxes.  In other implementations, basic regular expressions are less powerful.  The following description applies to extended regular expressions;  differences  for  basic  regular  expressions  are summarized   afterwards.    Perl  regular  expressions  give  additional  functionality,  and  are  documented  in  pcresyntax(3)  and pcrepattern(3), but may not be available on every system.

       The fundamental building blocks are the regular expressions that match a single character.  Most characters, including all letters and digits,  are  regular expressions that match themselves.  Any meta-character with special meaning may be quoted by preceding it with a backslash.

       The period . matches any single character.

   Character Classes and Bracket Expressions
       A bracket expression is a list of characters enclosed by [ and ].  It matches  any  single  character  in  that  list;  if  the  first character  of the list is the caret ^ then it matches any character not in the list.  For example, the regular expression [0123456789] matches any single digit.

       Within a bracket expression, a range expression consists of two characters separated by a hyphen.  It  matches  any  single  character that  sorts  between  the  two  characters,  inclusive,  using the locale’s collating sequence and character set.  For example, in the default C locale, [a-d] is equivalent to [abcd].  Many locales sort characters in dictionary order, and  in  these  locales  [a-d]  is typically  not  equivalent  to  [abcd]; it might be equivalent to [aBbCcDd], for example.  To obtain the traditional interpretation of bracket expressions, you can use the C locale by setting the LC_ALL environment variable to the value C.

       Finally, certain named classes of characters are predefined within bracket expressions, as follows.  Their names are self explanatory,
       and  they  are  [:alnum:],  [:alpha:],  [:cntrl:],  [:digit:],  [:graph:],  [:lower:], [:print:], [:punct:], [:space:], [:upper:], and [:xdigit:].  For example, [[:alnum:]] means [0-9A-Za-z], except the latter form depends upon the C  locale  and  the  ASCII  character encoding, whereas the former is independent of locale and character set.  (Note that the brackets in these class names are part of the symbolic names, and must be included in addition to the brackets delimiting the bracket expression.)  Most meta-characters lose  their special  meaning  inside  bracket  expressions.  To include a literal ] place it first in the list.  Similarly, to include a literal ^


       place it anywhere but first.  Finally, to include a literal - place it last.

   Anchoring
       The caret ^ and the dollar sign $ are meta-characters that respectively match the empty string at the beginning and end of a line.

   The Backslash Character and Special Expressions
       The symbols \< and \> respectively match the empty string at the beginning and end of a word.  The symbol \b matches the empty  string at  the  edge  of  a  word,  and  \B matches the empty string provided it’s not at the edge of a word.  The symbol \w is a synonym for [[:alnum:]] and \W is a synonym for [^[:alnum:]].

   Repetition
       A regular expression may be followed by one of several repetition operators:
       ?      The preceding item is optional and matched at most once.
       *      The preceding item will be matched zero or more times.
       +      The preceding item will be matched one or more times.
       {n}    The preceding item is matched exactly n times.
       {n,}   The preceding item is matched n or more times.
       {,m}   The preceding item is matched at most m times.
       {n,m}  The preceding item is matched at least n times, but not more than m times.

   Concatenation
       Two regular expressions may be concatenated; the  resulting  regular  expression  matches  any  string  formed  by  concatenating  two
       substrings that respectively match the concatenated expressions.

   Alternation
       Two  regular  expressions  may  be joined by the infix operator |; the resulting regular expression matches any string matching either alternate expression.

   Precedence
       Repetition takes precedence over concatenation, which in turn takes precedence over alternation.  A whole expression may  be  enclosed in parentheses to override these precedence rules and form a subexpression.

   Back References and Subexpressions
       The  back-reference  \n, where n is a single digit, matches the substring previously matched by the nth parenthesized subexpression of the regular expression.

   Basic vs Extended Regular Expressions
       In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \+, \{, \|, \(, and \).

       Traditional  egrep did not support the { meta-character, and some egrep implementations support \{ instead, so portable scripts should avoid { in grep -E patterns and should use [{] to match a literal {.

       GNU grep -E attempts to support traditional usage by assuming that { is not special if it would be the start of  an  invalid  interval
       specification.   For example, the command grep -E ’{1’ searches for the two-character string {1 instead of reporting a syntax error in the regular expression.  POSIX.2 allows this behavior as an extension, but portable scripts should avoid it.






Comments