1 \input texinfo @c -*-texinfo-*-
5 @settitle GNU Grep @value{VERSION}
17 This manual is for @command{grep}, a pattern matching engine.
19 Copyright @copyright{} 1999-2002, 2005, 2008-2010 Free Software Foundation,
23 Permission is granted to copy, distribute and/or modify this document
24 under the terms of the GNU Free Documentation License, Version 1.3 or
25 any later version published by the Free Software Foundation; with no
26 Invariant Sections, with no Front-Cover Texts, and with no Back-Cover
27 Texts. A copy of the license is included in the section entitled
28 ``GNU Free Documentation License''.
32 @dircategory Text creation and manipulation
34 * grep: (grep). Print lines matching a pattern.
38 @title GNU Grep: Print lines matching a pattern
39 @subtitle version @value{VERSION}, @value{UPDATED}
40 @author Alain Magloire et al.
42 @vskip 0pt plus 1filll
53 @command{grep} prints lines that match a pattern.
55 This manual is for version @value{VERSION} of GNU Grep.
61 * Introduction:: Introduction.
62 * Invoking:: Command-line options, environment, exit status.
63 * Regular Expressions:: Regular Expressions.
65 * Reporting Bugs:: Reporting Bugs.
66 * Copying:: License terms for this manual.
67 * Index:: Combined index.
74 @cindex searching for a pattern
76 @command{grep} searches the input files
77 for lines containing a match to a given pattern list.
78 When it finds a match in a line,
79 it copies the line to standard output (by default),
80 or produces whatever other sort of output you have requested with options.
82 Though @command{grep} expects to do the matching on text,
83 it has no limits on input line length other than available memory,
84 and it can match arbitrary characters within a line.
85 If the final byte of an input file is not a newline,
86 @command{grep} silently supplies one.
87 Since newline is also a separator for the list of patterns,
88 there is no way to match newline characters in a text.
92 @chapter Invoking @command{grep}
94 The general synopsis of the @command{grep} command line is
97 grep @var{options} @var{pattern} @var{input_file_names}
101 There can be zero or more @var{options}.
102 @var{pattern} will only be seen as such
103 (and not as an @var{input_file_name})
104 if it wasn't already specified within @var{options}
105 (by using the @samp{-e@ @var{pattern}}
106 or @samp{-f@ @var{file}} options).
107 There can be zero or more @var{input_file_names}.
110 * Command-line Options:: Short and long names, grouped by category.
111 * Environment Variables:: POSIX, GNU generic, and GNU grep specific.
112 * Exit Status:: Exit status returned by @command{grep}.
113 * grep Programs:: @command{grep} programs.
116 @node Command-line Options
117 @section Command-line Options
119 @command{grep} comes with a rich set of options:
120 some from @sc{posix.2} and some being @sc{gnu} extensions.
121 Long option names are always a @sc{gnu} extension,
122 even for options that are from @sc{posix} specifications.
123 Options that are specified by @sc{posix},
124 under their short names,
125 are explicitly marked as such
126 to facilitate @sc{posix}-portable programming.
127 A few option names are provided
128 for compatibility with older or more exotic implementations.
131 * Generic Program Information::
133 * General Output Control::
134 * Output Line Prefix Control::
135 * Context Line Control::
136 * File and Directory Selection::
140 Several additional options control
141 which variant of the @command{grep} matching engine is used.
142 @xref{grep Programs}.
144 @node Generic Program Information
145 @subsection Generic Program Information
151 @cindex usage summary, printing
152 Print a usage message briefly summarizing the command-line options
153 and the bug-reporting address, then exit.
159 @cindex version, printing
160 Print the version number of @command{grep} to the standard output stream.
161 This version number should be included in all bug reports.
165 @node Matching Control
166 @subsection Matching Control
170 @item -e @var{pattern}
171 @itemx --regexp=@var{pattern}
173 @opindex --regexp=@var{pattern}
175 Use @var{pattern} as the pattern.
176 This can be used to specify multiple search patterns,
177 or to protect a pattern beginning with a @samp{-}.
178 (@samp{-e} is specified by @sc{posix}.)
181 @itemx --file=@var{file}
184 @cindex pattern from file
185 Obtain patterns from @var{file}, one per line.
186 The empty file contains zero patterns, and therefore matches nothing.
187 (@samp{-f} is specified by @sc{posix}.)
194 @opindex --ignore-case
195 @cindex case insensitive search
196 Ignore case distinctions in both the pattern and the input files.
197 @samp{-y} is an obsolete synonym that is provided for compatibility.
198 (@samp{-i} is specified by @sc{posix}.)
201 @itemx --invert-match
203 @opindex --invert-match
204 @cindex invert matching
205 @cindex print non-matching lines
206 Invert the sense of matching, to select non-matching lines.
207 (@samp{-v} is specified by @sc{posix}.)
212 @opindex --word-regexp
213 @cindex matching whole words
214 Select only those lines containing matches that form whole words.
215 The test is that the matching substring must either
216 be at the beginning of the line,
217 or preceded by a non-word constituent character.
219 it must be either at the end of the line
220 or followed by a non-word constituent character.
221 Word-constituent characters are letters, digits, and the underscore.
226 @opindex --line-regexp
227 @cindex match the whole line
228 Select only those matches that exactly match the whole line.
229 (@samp{-x} is specified by @sc{posix}.)
233 @node General Output Control
234 @subsection General Output Control
242 @cindex counting lines
243 Suppress normal output;
244 instead print a count of matching lines for each input file.
245 With the @samp{-v}, @samp{--invert-match} option,
246 count non-matching lines.
247 (@samp{-c} is specified by @sc{posix}.)
249 @item --color[=@var{WHEN}]
250 @itemx --colour[=@var{WHEN}]
253 @cindex highlight, color, colour
254 Surround the matched (non-empty) strings, matching lines, context lines,
255 file names, line numbers, byte offsets, and separators (for fields and
256 groups of context lines) with escape sequences to display them in color
258 The colors are defined by the environment variable @var{GREP_COLORS}
259 and default to @samp{ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=32:bn=32:se=36}
260 for bold red matched text, magenta file names, green line numbers,
261 green byte offsets, cyan separators, and default terminal colors otherwise.
262 The deprecated environment variable @var{GREP_COLOR} is still supported,
263 but its setting does not have priority;
264 it defaults to `01;31' (bold red)
265 which only covers the color for matched text.
266 @var{WHEN} is @samp{never}, @samp{always}, or @samp{auto}.
269 @itemx --files-without-match
271 @opindex --files-without-match
272 @cindex files which don't match
273 Suppress normal output;
274 instead print the name of each input file from which
275 no output would normally have been printed.
276 The scanning of every file will stop on the first match.
279 @itemx --files-with-matches
281 @opindex --files-with-matches
282 @cindex names of matching files
283 Suppress normal output;
284 instead print the name of each input file from which
285 output would normally have been printed.
286 The scanning of every file will stop on the first match.
287 (@samp{-l} is specified by @sc{posix}.)
290 @itemx --max-count=@var{num}
294 Stop reading a file after @var{num} matching lines.
295 If the input is standard input from a regular file,
296 and @var{num} matching lines are output,
297 @command{grep} ensures that the standard input is positioned
298 just after the last matching line before exiting,
299 regardless of the presence of trailing context lines.
300 This enables a calling process to resume a search.
301 For example, the following shell script makes use of it:
304 while grep -m 1 PATTERN
310 But the following probably will not work because a pipe is not a regular
314 # This probably will not work.
316 while grep -m 1 PATTERN
322 When @command{grep} stops after @var{num} matching lines,
323 it outputs any trailing context lines.
324 Since context does not include matching lines,
325 @command{grep} will stop when it encounters another matching line.
326 When the @samp{-c} or @samp{--count} option is also used,
327 @command{grep} does not output a count greater than @var{num}.
328 When the @samp{-v} or @samp{--invert-match} option is also used,
329 @command{grep} stops after outputting @var{num} non-matching lines.
332 @itemx --only-matching
334 @opindex --only-matching
335 @cindex only matching
336 Print only the matched (non-empty) parts of matching lines,
337 with each such part on a separate output line.
345 @cindex quiet, silent
346 Quiet; do not write anything to standard output.
347 Exit immediately with zero status if any match is found,
348 even if an error was detected.
349 Also see the @samp{-s} or @samp{--no-messages} option.
350 (@samp{-q} is specified by @sc{posix}.)
355 @opindex --no-messages
356 @cindex suppress error messages
357 Suppress error messages about nonexistent or unreadable files.
359 unlike @sc{gnu} @command{grep},
360 7th Edition Unix @command{grep} did not conform to @sc{posix},
361 because it lacked @samp{-q}
362 and its @samp{-s} option behaved like
363 @sc{gnu} @command{grep}'s @samp{-q} option.
364 @sc{usg}-style @command{grep} also lacked @samp{-q}
365 but its @samp{-s} option behaved like @sc{gnu} @command{grep}'s.
366 Portable shell scripts should avoid both
367 @samp{-q} and @samp{-s} and should redirect
368 standard and error output to @file{/dev/null} instead.
369 (@samp{-s} is specified by @sc{posix}.)
373 @node Output Line Prefix Control
374 @subsection Output Line Prefix Control
376 When several prefix fields are to be output,
377 the order is always file name, line number, and byte offset,
378 regardless of the order in which these options were specified.
385 @opindex --byte-offset
387 Print the 0-based byte offset within the input file
388 before each line of output.
389 If @samp{-o} (@samp{--only-matching}) is specified,
390 print the offset of the matching part itself.
391 When @command{grep} runs on @sc{ms-dos} or @sc{ms}-Windows,
392 the printed byte offsets depend on whether
393 the @samp{-u} (@samp{--unix-byte-offsets}) option is used;
397 @itemx --with-filename
399 @opindex --with-filename
400 @cindex with filename prefix
401 Print the file name for each match.
402 This is the default when there is more than one file to search.
407 @opindex --no-filename
408 @cindex no filename prefix
409 Suppress the prefixing of file names on output.
410 This is the default when there is only one file
411 (or only standard input) to search.
413 @item --label=@var{LABEL}
415 @cindex changing name of standard input
416 Display input actually coming from standard input
417 as input coming from file @var{LABEL}. This is
418 especially useful when implementing tools like
419 @command{zgrep}; e.g.:
422 gzip -cd foo.gz | grep --label=foo -H something
428 @opindex --line-number
429 @cindex line numbering
430 Prefix each line of output with the 1-based line number within its input file.
431 (@samp{-n} is specified by @sc{posix}.)
436 @opindex --initial-tab
437 @cindex tab-aligned content lines
438 Make sure that the first character of actual line content lies on a tab stop,
439 so that the alignment of tabs looks normal.
440 This is useful with options that prefix their output to the actual content:
441 @samp{-H}, @samp{-n}, and @samp{-b}.
442 In order to improve the probability that lines
443 from a single file will all start at the same column,
444 this also causes the line number and byte offset (if present)
445 to be printed in a minimum-size field width.
448 @itemx --unix-byte-offsets
450 @opindex --unix-byte-offsets
451 @cindex @sc{ms-dos}/@sc{ms}-Windows byte offsets
452 @cindex byte offsets, on @sc{ms-dos}/@sc{ms}-Windows
453 Report Unix-style byte offsets.
454 This option causes @command{grep} to report byte offsets
455 as if the file were a Unix-style text file,
456 i.e., the byte offsets ignore the @code{CR} characters that were stripped.
457 This will produce results identical
458 to running @command{grep} on a Unix machine.
459 This option has no effect unless the @samp{-b} option is also used;
460 it has no effect on platforms other than @sc{ms-dos} and @sc{ms}-Windows.
466 @cindex zero-terminated file names
467 Output a zero byte (the @sc{ascii} @code{NUL} character)
468 instead of the character that normally follows a file name.
470 @samp{grep -lZ} outputs a zero byte after each file name
471 instead of the usual newline.
472 This option makes the output unambiguous,
473 even in the presence of file names containing unusual characters like newlines.
474 This option can be used with commands like
475 @samp{find -print0}, @samp{perl -0}, @samp{sort -z}, and @samp{xargs -0}
476 to process arbitrary file names,
477 even those that contain newline characters.
481 @node Context Line Control
482 @subsection Context Line Control
484 Regardless of how these options are set,
485 @command{grep} will never print any given line more than once.
486 If the @samp{-o} or @samp{--only-matching} option is specified,
487 these options have no effect and a warning is given upon their use.
492 @itemx --after-context=@var{num}
494 @opindex --after-context
495 @cindex after context
496 @cindex context lines, after match
497 Print @var{num} lines of trailing context after matching lines.
500 @itemx --before-context=@var{num}
502 @opindex --before-context
503 @cindex before context
504 @cindex context lines, before match
505 Print @var{num} lines of leading context before matching lines.
509 @itemx --context=@var{num}
514 Print @var{num} lines of leading and trailing output context.
516 @item --group-separator=@var{string}
517 @opindex --group-separator
518 @cindex group separator
519 When @option{-A}, @option{-B} or @option{-C} are in use,
520 print @var{string} instead of @samp{--} around disjoint groups
523 @item --no-group-separator
524 @opindex --group-separator
525 @cindex group separator
526 When @option{-A}, @option{-B} or @option{-C} are in use,
527 print disjoint groups of lines adjacent to each other.
531 Matching lines normally use @samp{:} as a separator
532 between prefix fields and actual line content.
533 Context (i.e., non-matching) lines use @samp{-} instead.
534 When no context is specified,
535 matching lines are simply output one right after another.
536 When nonzero context is specified,
537 lines that are adjacent in the input form a group
538 and are output one right after another, while
539 a separator appears by default between disjoint groups on a line
540 of its own and without any prefix. The default separator
541 is @samp{--}, however whether to include it and its appearance
542 can be changed with the options above. Each group may contain
543 several matching lines when they are close enough to each other
544 that two otherwise adjacent but divided groups connect
545 and can just merge into a single contiguous one.
547 @node File and Directory Selection
548 @subsection File and Directory Selection
556 @cindex suppress binary data
558 Process a binary file as if it were text;
559 this is equivalent to the @samp{--binary-files=text} option.
561 @itemx --binary-files=@var{type}
562 @opindex --binary-files
564 If the first few bytes of a file indicate that the file contains binary data,
565 assume that the file is of type @var{type}.
566 By default, @var{type} is @samp{binary},
567 and @command{grep} normally outputs either
568 a one-line message saying that a binary file matches,
569 or no message if there is no match.
570 If @var{type} is @samp{without-match},
571 @command{grep} assumes that a binary file does not match;
572 this is equivalent to the @samp{-I} option.
573 If @var{type} is @samp{text},
574 @command{grep} processes a binary file as if it were text;
575 this is equivalent to the @samp{-a} option.
576 @emph{Warning:} @samp{--binary-files=text} might output binary garbage,
577 which can have nasty side effects
578 if the output is a terminal and
579 if the terminal driver interprets some of it as commands.
581 @item -D @var{action}
582 @itemx --devices=@var{action}
585 @cindex device search
586 If an input file is a device, FIFO, or socket, use @var{action} to process it.
587 By default, @var{action} is @samp{read},
588 which means that devices are read just as if they were ordinary files.
589 If @var{action} is @samp{skip},
590 devices, FIFOs, and sockets are silently skipped.
592 @item -d @var{action}
593 @itemx --directories=@var{action}
595 @opindex --directories
596 @cindex directory search
597 If an input file is a directory, use @var{action} to process it.
598 By default, @var{action} is @samp{read},
599 which means that directories are read just as if they were ordinary files
600 (some operating systems and file systems disallow this,
601 and will cause @command{grep}
602 to print error messages for every directory or silently skip them).
603 If @var{action} is @samp{skip}, directories are silently skipped.
604 If @var{action} is @samp{recurse},
605 @command{grep} reads all files under each directory, recursively;
606 this is equivalent to the @samp{-r} option.
608 @item --exclude=@var{glob}
610 @cindex exclude files
611 @cindex searching directory trees
612 Skip files whose base name matches @var{glob}
613 (using wildcard matching).
614 A file-name glob can use
615 @samp{*}, @samp{?}, and @samp{[}...@samp{]} as wildcards,
616 and @code{\} to quote a wildcard or backslash character literally.
618 @item --exclude-from=@var{file}
619 @opindex --exclude-from
620 @cindex exclude files
621 @cindex searching directory trees
622 Skip files whose base name matches any of the file-name globs
623 read from @var{file} (using wildcard matching as described
624 under @samp{--exclude}).
626 @item --exclude-dir=@var{dir}
627 @opindex --exclude-dir
628 @cindex exclude directories
629 Exclude directories matching the pattern @var{dir} from recursive
633 Process a binary file as if it did not contain matching data;
634 this is equivalent to the @samp{--binary-files=without-match} option.
636 @item --include=@var{glob}
638 @cindex include files
639 @cindex searching directory trees
640 Search only files whose base name matches @var{glob}
641 (using wildcard matching as described under @samp{--exclude}).
648 @cindex recursive search
649 @cindex searching directory trees
650 For each directory mentioned on the command line,
651 read and process all files in that directory, recursively.
652 This is the same as the @samp{--directories=recurse} option.
657 @opindex --only-files
658 @cindex ignoring special files
659 @cindex ignoring symlinked directories
660 Ignore all special files, except for symlinks.
661 When recursing into directories, ignore symlinked directories as well.
666 @subsection Other Options
670 @item --line-buffered
671 @opindex --line-buffered
672 @cindex line buffering
673 Use line buffering on output.
674 This can cause a performance penalty.
678 @cindex memory mapped input
679 This option is ignored for backwards compatibility. It used to read
680 input with the @code{mmap} system call, instead of the default @code{read}
681 system call. On modern systems, @samp{--mmap} rarely if ever yields
688 @cindex @sc{ms-dos}/@sc{ms}-Windows binary files
689 @cindex binary files, @sc{ms-dos}/@sc{ms}-Windows
690 Treat the file(s) as binary.
691 By default, under @sc{ms-dos} and @sc{ms}-Windows,
692 @command{grep} guesses the file type
693 by looking at the contents of the first 32kB read from the file.
694 If @command{grep} decides the file is a text file,
695 it strips the @code{CR} characters from the original file contents
696 (to make regular expressions with @code{^} and @code{$} work correctly).
697 Specifying @samp{-U} overrules this guesswork,
698 causing all files to be read and passed to the matching mechanism verbatim;
699 if the file is a text file with @code{CR/LF} pairs at the end of each line,
700 this will cause some regular expressions to fail.
701 This option has no effect
702 on platforms other than @sc{ms-dos} and @sc{ms}-Windows.
708 @cindex zero-terminated lines
709 Treat the input as a set of lines, each terminated by a zero byte (the
710 @sc{ascii} @code{NUL} character) instead of a newline.
711 Like the @samp{-Z} or @samp{--null} option,
712 this option can be used with commands like
713 @samp{sort -z} to process arbitrary file names.
717 @node Environment Variables
718 @section Environment Variables
720 The behavior of @command{grep} is affected
721 by the following environment variables.
723 The locale for category @w{@code{LC_@var{foo}}}
724 is specified by examining the three environment variables
725 @env{LC_ALL}, @w{@env{LC_@var{foo}}}, and @env{LANG},
727 The first of these variables that is set specifies the locale.
728 For example, if @env{LC_ALL} is not set,
729 but @env{LC_MESSAGES} is set to @samp{pt_BR},
730 then the Brazilian Portuguese locale is used
731 for the @code{LC_MESSAGES} category.
732 The @samp{C} locale is used if none of these environment variables are set,
733 if the locale catalog is not installed,
734 or if @command{grep} was not compiled
735 with national language support (@sc{nls}).
737 @cindex environment variables
742 @vindex GREP_OPTIONS @r{environment variable}
743 @cindex default options environment variable
744 This variable specifies default options to be placed in front of any
746 For example, if @code{GREP_OPTIONS} is
747 @samp{--binary-files=without-match --directories=skip}, @command{grep}
748 behaves as if the two options @samp{--binary-files=without-match} and
749 @samp{--directories=skip} had been specified before
750 any explicit options.
751 Option specifications are separated by
753 A backslash escapes the next character, so it can be used to
754 specify an option containing whitespace or a backslash.
757 @vindex GREP_COLOR @r{environment variable}
758 @cindex highlight markers
759 This variable specifies the color used to highlight matched (non-empty) text.
760 It is deprecated in favor of @code{GREP_COLORS}, but still supported.
761 The @samp{mt}, @samp{ms}, and @samp{mc} capabilities of @code{GREP_COLORS}
762 have priority over it.
763 It can only specify the color used to highlight
764 the matching non-empty text in any matching line
765 (a selected line when the @samp{-v} command-line option is omitted,
766 or a context line when @samp{-v} is specified).
767 The default is @samp{01;31},
768 which means a bold red foreground text on the terminal's default background.
771 @vindex GREP_COLORS @r{environment variable}
772 @cindex highlight markers
773 This variable specifies the colors and other attributes
774 used to highlight various parts of the output.
775 Its value is a colon-separated list of capabilities
776 that defaults to @samp{ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=32:bn=32:se=36}
777 with the @samp{rv} and @samp{ne} boolean capabilities omitted (i.e., false).
778 Supported capabilities are as follows.
782 @vindex sl GREP_COLORS @r{capability}
783 SGR substring for whole selected lines
785 matching lines when the @samp{-v} command-line option is omitted,
786 or non-matching lines when @samp{-v} is specified).
787 If however the boolean @samp{rv} capability
788 and the @samp{-v} command-line option are both specified,
789 it applies to context matching lines instead.
790 The default is empty (i.e., the terminal's default color pair).
793 @vindex cx GREP_COLORS @r{capability}
794 SGR substring for whole context lines
796 non-matching lines when the @samp{-v} command-line option is omitted,
797 or matching lines when @samp{-v} is specified).
798 If however the boolean @samp{rv} capability
799 and the @samp{-v} command-line option are both specified,
800 it applies to selected non-matching lines instead.
801 The default is empty (i.e., the terminal's default color pair).
804 @vindex rv GREP_COLORS @r{capability}
805 Boolean value that reverses (swaps) the meanings of
806 the @samp{sl=} and @samp{cx=} capabilities
807 when the @samp{-v} command-line option is specified.
808 The default is false (i.e., the capability is omitted).
811 @vindex mt GREP_COLORS @r{capability}
812 SGR substring for matching non-empty text in any matching line
814 a selected line when the @samp{-v} command-line option is omitted,
815 or a context line when @samp{-v} is specified).
816 Setting this is equivalent to setting both @samp{ms=} and @samp{mc=}
817 at once to the same value.
818 The default is a bold red text foreground over the current line background.
821 @vindex ms GREP_COLORS @r{capability}
822 SGR substring for matching non-empty text in a selected line.
823 (This is only used when the @samp{-v} command-line option is omitted.)
824 The effect of the @samp{sl=} (or @samp{cx=} if @samp{rv}) capability
825 remains active when this kicks in.
826 The default is a bold red text foreground over the current line background.
829 @vindex mc GREP_COLORS @r{capability}
830 SGR substring for matching non-empty text in a context line.
831 (This is only used when the @samp{-v} command-line option is specified.)
832 The effect of the @samp{cx=} (or @samp{sl=} if @samp{rv}) capability
833 remains active when this kicks in.
834 The default is a bold red text foreground over the current line background.
837 @vindex fn GREP_COLORS @r{capability}
838 SGR substring for file names prefixing any content line.
839 The default is a magenta text foreground over the terminal's default background.
842 @vindex ln GREP_COLORS @r{capability}
843 SGR substring for line numbers prefixing any content line.
844 The default is a green text foreground over the terminal's default background.
847 @vindex bn GREP_COLORS @r{capability}
848 SGR substring for byte offsets prefixing any content line.
849 The default is a green text foreground over the terminal's default background.
852 @vindex fn GREP_COLORS @r{capability}
853 SGR substring for separators that are inserted
854 between selected line fields (@samp{:}),
855 between context line fields (@samp{-}),
856 and between groups of adjacent lines
857 when nonzero context is specified (@samp{--}).
858 The default is a cyan text foreground over the terminal's default background.
861 @vindex ne GREP_COLORS @r{capability}
862 Boolean value that prevents clearing to the end of line
863 using Erase in Line (EL) to Right (@samp{\33[K})
864 each time a colorized item ends.
865 This is needed on terminals on which EL is not supported.
866 It is otherwise useful on terminals
867 for which the @code{back_color_erase}
868 (@code{bce}) boolean terminfo capability does not apply,
869 when the chosen highlight colors do not affect the background,
870 or when EL is too slow or causes too much flicker.
871 The default is false (i.e., the capability is omitted).
874 Note that boolean capabilities have no @samp{=}... part.
875 They are omitted (i.e., false) by default and become true when specified.
877 See the Select Graphic Rendition (SGR) section
878 in the documentation of your text terminal
879 for permitted values and their meaning as character attributes.
880 These substring values are integers in decimal representation
881 and can be concatenated with semicolons.
882 @command{grep} takes care of assembling the result
883 into a complete SGR sequence (@samp{\33[}...@samp{m}).
884 Common values to concatenate include
886 @samp{4} for underline,
888 @samp{7} for inverse,
889 @samp{39} for default foreground color,
890 @samp{30} to @samp{37} for foreground colors,
891 @samp{90} to @samp{97} for 16-color mode foreground colors,
892 @samp{38;5;0} to @samp{38;5;255}
893 for 88-color and 256-color modes foreground colors,
894 @samp{49} for default background color,
895 @samp{40} to @samp{47} for background colors,
896 @samp{100} to @samp{107} for 16-color mode background colors,
897 and @samp{48;5;0} to @samp{48;5;255}
898 for 88-color and 256-color modes background colors.
903 @vindex LC_ALL @r{environment variable}
904 @vindex LC_COLLATE @r{environment variable}
905 @vindex LANG @r{environment variable}
906 @cindex character type
907 @cindex national language support
909 These variables specify the locale for the @code{LC_COLLATE} category,
910 which determines the collating sequence
911 used to interpret range expressions like @samp{[a-z]}.
916 @vindex LC_ALL @r{environment variable}
917 @vindex LC_CTYPE @r{environment variable}
918 @vindex LANG @r{environment variable}
919 These variables specify the locale for the @code{LC_CTYPE} category,
920 which determines the type of characters,
921 e.g., which characters are whitespace.
926 @vindex LC_ALL @r{environment variable}
927 @vindex LC_MESSAGES @r{environment variable}
928 @vindex LANG @r{environment variable}
929 @cindex language of messages
930 @cindex message language
931 @cindex national language support
932 @cindex translation of message language
933 These variables specify the locale for the @code{LC_MESSAGES} category,
934 which determines the language that @command{grep} uses for messages.
935 The default @samp{C} locale uses American English messages.
937 @item POSIXLY_CORRECT
938 @vindex POSIXLY_CORRECT @r{environment variable}
939 If set, @command{grep} behaves as @sc{posix.2} requires; otherwise,
940 @command{grep} behaves more like other @sc{gnu} programs.
942 requires that options that
943 follow file names must be treated as file names;
945 such options are permuted to the front of the operand list
946 and are treated as options.
947 Also, @code{POSIXLY_CORRECT} disables special handling of an
948 invalid bracket expression. @xref{invalid-bracket-expr}.
950 @item _@var{N}_GNU_nonoption_argv_flags_
951 @vindex _@var{N}_GNU_nonoption_argv_flags_ @r{environment variable}
952 (Here @code{@var{N}} is @command{grep}'s numeric process ID.)
953 If the @var{i}th character of this environment variable's value is @samp{1},
954 do not consider the @var{i}th operand of @command{grep} to be an option,
955 even if it appears to be one.
956 A shell can put this variable in the environment for each command it runs,
957 specifying which operands are the results of file name wildcard expansion
958 and therefore should not be treated as options.
959 This behavior is available only with the @sc{gnu} C library,
960 and only when @code{POSIXLY_CORRECT} is not set.
968 @cindex return status
970 Normally, the exit status is 0 if selected lines are found and 1 otherwise.
971 But the exit status is 2 if an error occurred, unless the @option{-q} or
972 @option{--quiet} or @option{--silent} option is used and a selected line
974 Note, however, that @sc{posix} only mandates,
975 for programs such as @command{grep}, @command{cmp}, and @command{diff},
976 that the exit status in case of error be greater than 1;
977 it is therefore advisable, for the sake of portability,
978 to use logic that tests for this general condition
979 instead of strict equality with@ 2.
983 @section @command{grep} Programs
984 @cindex @command{grep} programs
985 @cindex variants of @command{gerp}
987 @command{grep} searches the named input files
988 (or standard input if no files are named,
989 or the file name @file{-} is given)
990 for lines containing a match to the given pattern.
991 By default, @command{grep} prints the matching lines.
992 There are four major variants of @command{grep},
993 controlled by the following options.
998 @itemx --basic-regexp
1000 @opindex --basic-regexp
1001 @cindex matching basic regular expressions
1002 Interpret the pattern as a basic regular expression (BRE).
1003 This is the default.
1006 @itemx --extended-regexp
1008 @opindex --extended-regexp
1009 @cindex matching extended regular expressions
1010 Interpret the pattern as an extended regular expression (ERE).
1011 (@samp{-E} is specified by @sc{posix}.)
1014 @itemx --fixed-strings
1016 @opindex --fixed-strings
1017 @cindex matching fixed strings
1018 Interpret the pattern as a list of fixed strings, separated
1019 by newlines, any of which is to be matched.
1020 (@samp{-F} is specified by @sc{posix}.)
1023 @itemx --perl-regexp
1025 @opindex --perl-regexp
1026 @cindex matching Perl regular expressions
1027 Interpret the pattern as a Perl regular expression.
1028 This is highly experimental and
1029 @samp{grep@ -P} may warn of unimplemented features.
1034 two variant programs @command{egrep} and @command{fgrep} are available.
1035 @command{egrep} is the same as @samp{grep@ -E}.
1036 @command{fgrep} is the same as @samp{grep@ -F}.
1037 Direct invocation as either
1038 @command{egrep} or @command{fgrep} is deprecated,
1039 but is provided to allow historical applications
1040 that rely on them to run unmodified.
1043 @node Regular Expressions
1044 @chapter Regular Expressions
1045 @cindex regular expressions
1047 A @dfn{regular expression} is a pattern that describes a set of strings.
1048 Regular expressions are constructed analogously to arithmetic expressions,
1049 by using various operators to combine smaller expressions.
1050 @command{grep} understands
1051 three different versions of regular expression syntax:
1052 ``basic,'' (BRE) ``extended'' (ERE) and ``perl''.
1053 In @sc{gnu} @command{grep},
1054 there is no difference in available functionality between basic and
1056 In other implementations, basic regular expressions are less powerful.
1057 The following description applies to extended regular expressions;
1058 differences for basic regular expressions are summarized afterwards.
1059 Perl regular expressions give additional functionality, and are
1060 documented in pcresyntax(3) and pcrepattern(3), but may not be
1061 available on every system.
1064 * Fundamental Structure::
1065 * Character Classes and Bracket Expressions::
1066 * The Backslash Character and Special Expressions::
1068 * Back-references and Subexpressions::
1069 * Basic vs Extended::
1072 @node Fundamental Structure
1073 @section Fundamental Structure
1075 The fundamental building blocks are the regular expressions that match
1077 Most characters, including all letters and digits,
1078 are regular expressions that match themselves.
1080 with special meaning may be quoted by preceding it with a backslash.
1082 A regular expression may be followed by one of several
1083 repetition operators:
1091 The period @samp{.} matches any single character.
1095 @cindex question mark
1096 @cindex match expression at most once
1097 The preceding item is optional and will be matched at most once.
1102 @cindex match expression zero or more times
1103 The preceding item will be matched zero or more times.
1108 @cindex match expression one or more times
1109 The preceding item will be matched one or more times.
1112 @opindex @{@var{n}@}
1113 @cindex braces, one argument
1114 @cindex match expression @var{n} times
1115 The preceding item is matched exactly @var{n} times.
1118 @opindex @{@var{n},@}
1119 @cindex braces, second argument omitted
1120 @cindex match expression @var{n} or more times
1121 The preceding item is matched @var{n} or more times.
1124 @opindex @{,@var{m}@}
1125 @cindex braces, first argument omitted
1126 @cindex match expression at most @var{m} times
1127 The preceding item is matched at most @var{m} times.
1129 @item @{@var{n},@var{m}@}
1130 @opindex @{@var{n},@var{m}@}
1131 @cindex braces, two arguments
1132 @cindex match expression from @var{n} to @var{m} times
1133 The preceding item is matched at least @var{n} times, but not more than
1138 Two regular expressions may be concatenated;
1139 the resulting regular expression
1140 matches any string formed by concatenating two substrings
1141 that respectively match the concatenated expressions.
1143 Two regular expressions may be joined by the infix operator @samp{|};
1144 the resulting regular expression
1145 matches any string matching either alternalte expression.
1147 Repetition takes precedence over concatenation,
1148 which in turn takes precedence over alternation.
1149 A whole expression may be enclosed in parentheses
1150 to override these precedence rules and form a subexpression.
1152 @node Character Classes and Bracket Expressions
1153 @section Character Classes and Bracket Expressions
1155 @cindex bracket expression
1156 @cindex character class
1157 A @dfn{bracket expression} is a list of characters enclosed by @samp{[} and
1159 It matches any single character in that list;
1160 if the first character of the list is the caret @samp{^},
1161 then it matches any character @strong{not} in the list.
1162 For example, the regular expression
1163 @samp{[0123456789]} matches any single digit.
1165 @cindex range expression
1166 Within a bracket expression, a @dfn{range expression} consists of two
1167 characters separated by a hyphen.
1168 It matches any single character that
1169 sorts between the two characters, inclusive, using the locale's
1170 collating sequence and character set.
1171 For example, in the default C
1172 locale, @samp{[a-d]} is equivalent to @samp{[abcd]}.
1174 characters in dictionary order, and in these locales @samp{[a-d]} is
1175 typically not equivalent to @samp{[abcd]};
1176 it might be equivalent to @samp{[aBbCcDd]}, for example.
1177 To obtain the traditional interpretation
1178 of bracket expressions, you can use the @samp{C} locale by setting the
1179 @env{LC_ALL} environment variable to the value @samp{C}.
1181 Finally, certain named classes of characters are predefined within
1182 bracket expressions, as follows.
1183 Their interpretation depends on the @code{LC_CTYPE} locale;
1184 the interpretation below is that of the @samp{C} locale,
1185 which is the default if no @code{LC_CTYPE} locale is specified.
1187 @cindex classes of characters
1188 @cindex character classes
1192 @opindex alnum @r{character class}
1193 @cindex alphanumeric characters
1194 Alphanumeric characters:
1195 @samp{[:alpha:]} and @samp{[:digit:]}.
1198 @opindex alpha @r{character class}
1199 @cindex alphabetic characters
1200 Alphabetic characters:
1201 @samp{[:lower:]} and @samp{[:upper:]}.
1204 @opindex blank @r{character class}
1205 @cindex blank characters
1210 @opindex cntrl @r{character class}
1211 @cindex control characters
1213 In @sc{ascii}, these characters have octal codes 000
1214 through 037, and 177 (@code{DEL}).
1215 In other character sets, these are
1216 the equivalent characters, if any.
1219 @opindex digit @r{character class}
1220 @cindex digit characters
1221 @cindex numeric characters
1222 Digits: @code{0 1 2 3 4 5 6 7 8 9}.
1225 @opindex graph @r{character class}
1226 @cindex graphic characters
1227 Graphical characters:
1228 @samp{[:alnum:]} and @samp{[:punct:]}.
1231 @opindex lower @r{character class}
1232 @cindex lower-case letters
1234 @code{a b c d e f g h i j k l m n o p q r s t u v w x y z}.
1237 @opindex print @r{character class}
1238 @cindex printable characters
1239 Printable characters:
1240 @samp{[:alnum:]}, @samp{[:punct:]}, and space.
1243 @opindex punct @r{character class}
1244 @cindex punctuation characters
1245 Punctuation characters:
1246 @code{!@: " # $ % & ' ( ) * + , - .@: / : ; < = > ?@: @@ [ \ ] ^ _ ` @{ | @} ~}.
1249 @opindex space @r{character class}
1250 @cindex space characters
1251 @cindex whitespace characters
1253 tab, newline, vertical tab, form feed, carriage return, and space.
1254 @xref{Usage}, for more discussion of matching newlines.
1257 @opindex upper @r{character class}
1258 @cindex upper-case letters
1260 @code{A B C D E F G H I J K L M N O P Q R S T U V W X Y Z}.
1263 @opindex xdigit @r{character class}
1264 @cindex xdigit class
1265 @cindex hexadecimal digits
1267 @code{0 1 2 3 4 5 6 7 8 9 A B C D E F a b c d e f}.
1270 For example, @samp{[[:alnum:]]} means @samp{[0-9A-Za-z]}, except the latter
1271 depends upon the @samp{C} locale and the @sc{ascii} character
1272 encoding, whereas the former is independent of locale and character set.
1273 (Note that the brackets in these class names are
1274 part of the symbolic names, and must be included in addition to
1275 the brackets delimiting the bracket expression.)
1277 @anchor{invalid-bracket-expr}
1278 If you mistakenly omit the outer brackets, and search for say, @samp{[:upper:]},
1279 GNU @command{grep} prints a diagnostic and exits with status 2, on
1280 the assumption that you did not intend to search for the nominally
1281 equivalent regular expression: @samp{[:epru]}.
1282 Set the @code{POSIXLY_CORRECT} environment variable to disable this feature.
1284 Most meta-characters lose their special meaning inside bracket expressions.
1288 ends the bracket expression if it's not the first list item.
1289 So, if you want to make the @samp{]} character a list item,
1290 you must put it first.
1293 represents the open collating symbol.
1296 represents the close collating symbol.
1299 represents the open equivalence class.
1302 represents the close equivalence class.
1305 represents the open character class symbol, and should be followed by a valid character class name.
1308 represents the close character class symbol.
1311 represents the range if it's not first or last in a list or the ending point
1315 represents the characters not in the list.
1316 If you want to make the @samp{^}
1317 character a list item, place it anywhere but first.
1321 @node The Backslash Character and Special Expressions
1322 @section The Backslash Character and Special Expressions
1325 The @samp{\} character,
1326 when followed by certain ordinary characters,
1327 takes a special meaning:
1332 Match the empty string at the edge of a word.
1335 Match the empty string provided it's not at the edge of a word.
1338 Match the empty string at the beginning of word.
1341 Match the empty string at the end of word.
1344 Match word constituent, it is a synonym for @samp{[[:alnum:]]}.
1347 Match non-word constituent, it is a synonym for @samp{[^[:alnum:]]}.
1350 Match whitespace, it is a synonym for @samp{[[:space:]]}.
1353 Match non-whitespace, it is a synonym for @samp{[^[:space:]]}.
1357 For example, @samp{\brat\b} matches the separate word @samp{rat},
1358 @samp{\Brat\B} matches @samp{crate} but not @samp{furry rat}.
1364 The caret @samp{^} and the dollar sign @samp{$} are meta-characters that
1365 respectively match the empty string at the beginning and end of a line.
1367 @node Back-references and Subexpressions
1368 @section Back-references and Subexpressions
1369 @cindex subexpression
1370 @cindex back-reference
1372 The back-reference @samp{\@var{n}}, where @var{n} is a single digit, matches
1373 the substring previously matched by the @var{n}th parenthesized subexpression
1374 of the regular expression.
1375 For example, @samp{(a)\1} matches @samp{aa}.
1376 When used with alternation, if the group does not participate in the match then
1377 the back-reference makes the whole match fail.
1378 For example, @samp{a(.)|b\1}
1379 will not match @samp{ba}.
1380 When multiple regular expressions are given with
1381 @samp{-e} or from a file (@samp{-f file}),
1382 back-references are local to each expression.
1384 @node Basic vs Extended
1385 @section Basic vs Extended Regular Expressions
1386 @cindex basic regular expressions
1388 In basic regular expressions the meta-characters @samp{?}, @samp{+},
1389 @samp{@{}, @samp{|}, @samp{(}, and @samp{)} lose their special meaning;
1390 instead use the backslashed versions @samp{\?}, @samp{\+}, @samp{\@{},
1391 @samp{\|}, @samp{\(}, and @samp{\)}.
1393 @cindex interval specifications
1394 Traditional @command{egrep} did not support the @samp{@{} meta-character,
1395 and some @command{egrep} implementations support @samp{\@{} instead, so
1396 portable scripts should avoid @samp{@{} in @samp{grep@ -E} patterns and
1397 should use @samp{[@{]} to match a literal @samp{@{}.
1399 @sc{gnu} @command{grep@ -E} attempts to support traditional usage by
1400 assuming that @samp{@{} is not special if it would be the start of an
1401 invalid interval specification.
1402 For example, the command
1403 @samp{grep@ -E@ '@{1'} searches for the two-character string @samp{@{1}
1404 instead of reporting a syntax error in the regular expression.
1405 @sc{posix.2} allows this behavior as an extension, but portable scripts
1412 @cindex usage, examples
1413 Here is an example command that invokes @sc{gnu} @command{grep}:
1416 grep -i 'hello.*world' menu.h main.c
1420 This lists all lines in the files @file{menu.h} and @file{main.c} that
1421 contain the string @samp{hello} followed by the string @samp{world};
1422 this is because @samp{.*} matches zero or more characters within a line.
1423 @xref{Regular Expressions}.
1424 The @samp{-i} option causes @command{grep}
1425 to ignore case, causing it to match the line @samp{Hello, world!}, which
1426 it would not otherwise match.
1427 @xref{Invoking}, for more details about
1428 how to invoke @command{grep}.
1430 @cindex using @command{grep}, Q&A
1431 @cindex FAQ about @command{grep} usage
1432 Here are some common questions and answers about @command{grep} usage.
1437 How can I list just the names of matching files?
1444 lists the names of all C files in the current directory whose contents
1445 mention @samp{main}.
1448 How do I search directories recursively?
1451 grep -r 'hello' /home/gigi
1455 searches for @samp{hello} in all files
1456 under the @file{/home/gigi} directory.
1457 For more control over which files are searched,
1458 use @command{find}, @command{grep}, and @command{xargs}.
1459 For example, the following command searches only C files:
1462 find /home/gigi -name '*.c' -print0 | xargs -0r grep -H 'hello'
1465 This differs from the command:
1468 grep -rH 'hello' *.c
1471 which merely looks for @samp{hello} in all files in the current
1472 directory whose names end in @samp{.c}.
1473 Here the @option{-r} is
1474 probably unnecessary, as recursion occurs only in the unlikely event
1475 that one of @samp{.c} files is a directory.
1476 The @samp{find ...} command line above is more similar to the command:
1479 grep -rH --include='*.c' 'hello' /home/gigi
1483 What if a pattern has a leading @samp{-}?
1486 grep -e '--cut here--' *
1490 searches for all lines matching @samp{--cut here--}.
1492 @command{grep} would attempt to parse @samp{--cut here--} as a list of
1496 Suppose I want to search for a whole word, not a part of a word?
1503 searches only for instances of @samp{hello} that are entire words;
1504 it does not match @samp{Othello}.
1505 For more control, use @samp{\<} and
1506 @samp{\>} to match the start and end of words.
1514 searches only for words ending in @samp{hello}, so it matches the word
1518 How do I output context around the matching lines?
1525 prints two lines of context around each matching line.
1528 How do I force @command{grep} to print the name of the file?
1530 Append @file{/dev/null}:
1533 grep 'eli' /etc/passwd /dev/null
1539 /etc/passwd:eli:x:2098:1000:Eli Smith:/home/eli:/bin/bash
1542 Alternatively, use @samp{-H}, which is a @sc{gnu} extension:
1545 grep -H 'eli' /etc/passwd
1549 Why do people use strange regular expressions on @command{ps} output?
1552 ps -ef | grep '[c]ron'
1555 If the pattern had been written without the square brackets, it would
1556 have matched not only the @command{ps} output line for @command{cron},
1557 but also the @command{ps} output line for @command{grep}.
1558 Note that on some platforms,
1559 @command{ps} limits the output to the width of the screen;
1560 @command{grep} does not have any limit on the length of a line
1561 except the available memory.
1564 Why does @command{grep} report ``Binary file matches''?
1566 If @command{grep} listed all matching ``lines'' from a binary file, it
1567 would probably generate output that is not useful, and it might even
1568 muck up your display.
1569 So @sc{gnu} @command{grep} suppresses output from
1570 files that appear to be binary files.
1571 To force @sc{gnu} @command{grep}
1572 to output lines even from files that appear to be binary, use the
1573 @samp{-a} or @samp{--binary-files=text} option.
1575 ``Binary file matches'' messages, use the @samp{-I} or
1576 @samp{--binary-files=without-match} option.
1579 Why doesn't @samp{grep -lv} print non-matching file names?
1581 @samp{grep -lv} lists the names of all files containing one or more
1582 lines that do not match.
1583 To list the names of all files that contain no
1584 matching lines, use the @samp{-L} or @samp{--files-without-match}
1588 I can do @sc{or} with @samp{|}, but what about @sc{and}?
1591 grep 'paul' /etc/motd | grep 'franc,ois'
1595 finds all lines that contain both @samp{paul} and @samp{franc,ois}.
1598 How can I search in both standard input and in files?
1600 Use the special file name @samp{-}:
1603 cat /etc/passwd | grep 'alain' - /etc/motd
1608 How to express palindromes in a regular expression?
1610 It can be done by using back-references;
1612 a palindrome of 4 characters can be written with a BRE:
1615 grep -w -e '\(.\)\(.\).\2\1' file
1618 It matches the word "radar" or "civic".
1620 Guglielmo Bondioni proposed a single RE
1621 that finds all palindromes up to 19 characters long
1622 using @w{9 subexpressions} and @w{9 back-references}:
1625 grep -E -e '^(.?)(.?)(.?)(.?)(.?)(.?)(.?)(.?)(.?).?\9\8\7\6\5\4\3\2\1$' file
1628 Note this is done by using @sc{gnu} ERE extensions;
1629 it might not be portable to other implementations of @command{grep}.
1632 Why is this back-reference failing?
1635 echo 'ba' | grep -E '(a)\1|b\1'
1638 This gives no output, because the first alternate @samp{(a)\1} does not match,
1639 as there is no @samp{aa} in the input, so the @samp{\1} in the second alternate
1640 has nothing to refer back to, meaning it will never match anything.
1641 (The second alternate in this example can only match
1642 if the first alternate has matched---making the second one superfluous.)
1645 How can I match across lines?
1647 Standard grep cannot do this, as it is fundamentally line-based.
1648 Therefore, merely using the @code{[:space:]} character class does not
1649 match newlines in the way you might expect. However, if your grep is
1650 compiled with Perl patterns enabled, the Perl @samp{s}
1651 modifier (which makes @code{.} match newlines) can be used:
1654 printf 'foo\nbar\n' | grep -P '(?s)foo.*?bar'
1657 With the GNU @command{grep} option @code{-z} (@pxref{File and
1658 Directory Selection}), the input is terminated by null bytes. Thus,
1659 you can match newlines in the input, but the output will be the whole
1660 file, so this is really only useful to determine if the pattern is
1664 printf 'foo\nbar\n' | grep -z -q 'foo[[:space:]]\+bar'
1667 Failing either of those options, you need to transform the input
1668 before giving it to @command{grep}, or turn to @command{awk},
1669 @command{sed}, @command{perl}, or many other utilities that are
1670 designed to operate across lines.
1673 What do @command{grep}, @command{fgrep}, and @command{egrep} stand for?
1675 The name @command{grep} comes from the way line editing was done on Unix.
1677 @command{ed} uses the following syntax
1678 to print a list of matching lines on the screen:
1681 global/regular expression/print
1685 @command{fgrep} stands for Fixed @command{grep};
1686 @command{egrep} stands for Extended @command{grep}.
1691 @node Reporting Bugs
1692 @chapter Reporting bugs
1694 @cindex bugs, reporting
1695 Email bug reports to @email{bug-grep@@gnu.org},
1696 a mailing list whose web page is
1697 @url{http://lists.gnu.org/mailman/listinfo/bug-grep}.
1698 The Savannah bug tracker for @command{grep} is located at
1699 @url{http://savannah.gnu.org/bugs/?group=grep}.
1704 Large repetition counts in the @samp{@{n,m@}} construct may cause
1705 @command{grep} to use lots of memory.
1706 In addition, certain other
1707 obscure regular expressions require exponential time and
1708 space, and may cause @command{grep} to run out of memory.
1710 Back-references are very slow, and may require exponential time.
1717 GNU grep is licensed under the GNU GPL, which makes it @dfn{free
1720 The ``free'' in ``free software'' refers to liberty, not price. As
1721 some GNU project advocates like to point out, think of ``free speech''
1722 rather than ``free beer''. In short, you have the right (freedom) to
1723 run and change grep and distribute it to other people, and---if you
1724 want---charge money for doing either. The important restriction is
1725 that you have to grant your recipients the same rights and impose the
1728 This general method of licensing software is sometimes called
1729 @dfn{open source}. The GNU project prefers the term ``free software''
1730 for reasons outlined at
1731 @url{http://www.gnu.org/philosophy/open-source-misses-the-point.html}.
1733 This manual is free documentation in the same sense. The
1734 documentation license is included below. The license for the program
1735 is available with the source code, or at
1736 @url{http://www.gnu.org/licenses/gpl.html}.
1739 * GNU Free Documentation License::
1742 @node GNU Free Documentation License
1743 @section GNU Free Documentation License