Upgrade grep version 2.7 to 2.9 on the vendor branch
[dragonfly.git] / contrib / grep / doc / grep.texi
1 \input texinfo  @c -*-texinfo-*-
2 @c %**start of header
3 @setfilename grep.info
4 @include version.texi
5 @settitle GNU Grep @value{VERSION}
6
7 @c Combine indices.
8 @syncodeindex ky cp
9 @syncodeindex pg cp
10 @syncodeindex tp cp
11 @defcodeindex op
12 @syncodeindex op cp
13 @syncodeindex vr cp
14 @c %**end of header
15
16 @copying
17 This manual is for @command{grep}, a pattern matching engine.
18
19 Copyright @copyright{} 1999-2002, 2005, 2008-2011 Free Software Foundation, Inc.
20
21 @quotation
22 Permission is granted to copy, distribute and/or modify this document
23 under the terms of the GNU Free Documentation License, Version 1.3 or
24 any later version published by the Free Software Foundation; with no
25 Invariant Sections, with no Front-Cover Texts, and with no Back-Cover
26 Texts.  A copy of the license is included in the section entitled
27 ``GNU Free Documentation License''.
28 @end quotation
29 @end copying
30
31 @dircategory Text creation and manipulation
32 @direntry
33 * grep: (grep).                 Print lines matching a pattern.
34 @end direntry
35
36 @titlepage
37 @title GNU Grep: Print lines matching a pattern
38 @subtitle version @value{VERSION}, @value{UPDATED}
39 @author Alain Magloire et al.
40 @page
41 @vskip 0pt plus 1filll
42 @insertcopying
43 @end titlepage
44
45 @contents
46
47
48 @ifnottex
49 @node Top
50 @top grep
51
52 @command{grep} prints lines that match a pattern.
53
54 This manual is for version @value{VERSION} of GNU Grep.
55
56 @insertcopying
57 @end ifnottex
58
59 @menu
60 * Introduction::                Introduction.
61 * Invoking::                    Command-line options, environment, exit status.
62 * Regular Expressions::         Regular Expressions.
63 * Usage::                       Examples.
64 * Reporting Bugs::              Reporting Bugs.
65 * Copying::                     License terms for this manual.
66 * Index::                       Combined index.
67 @end menu
68
69
70 @node Introduction
71 @chapter Introduction
72
73 @cindex searching for a pattern
74
75 @command{grep} searches the input files
76 for lines containing a match to a given pattern list.
77 When it finds a match in a line,
78 it copies the line to standard output (by default),
79 or produces whatever other sort of output you have requested with options.
80
81 Though @command{grep} expects to do the matching on text,
82 it has no limits on input line length other than available memory,
83 and it can match arbitrary characters within a line.
84 If the final byte of an input file is not a newline,
85 @command{grep} silently supplies one.
86 Since newline is also a separator for the list of patterns,
87 there is no way to match newline characters in a text.
88
89
90 @node Invoking
91 @chapter Invoking @command{grep}
92
93 The general synopsis of the @command{grep} command line is
94
95 @example
96 grep @var{options} @var{pattern} @var{input_file_names}
97 @end example
98
99 @noindent
100 There can be zero or more @var{options}.
101 @var{pattern} will only be seen as such
102 (and not as an @var{input_file_name})
103 if it wasn't already specified within @var{options}
104 (by using the @samp{-e@ @var{pattern}}
105 or @samp{-f@ @var{file}} options).
106 There can be zero or more @var{input_file_names}.
107
108 @menu
109 * Command-line Options::        Short and long names, grouped by category.
110 * Environment Variables::       POSIX, GNU generic, and GNU grep specific.
111 * Exit Status::                 Exit status returned by @command{grep}.
112 * grep Programs::               @command{grep} programs.
113 @end menu
114
115 @node Command-line Options
116 @section Command-line Options
117
118 @command{grep} comes with a rich set of options:
119 some from @sc{posix.2} and some being @sc{gnu} extensions.
120 Long option names are always a @sc{gnu} extension,
121 even for options that are from @sc{posix} specifications.
122 Options that are specified by @sc{posix},
123 under their short names,
124 are explicitly marked as such
125 to facilitate @sc{posix}-portable programming.
126 A few option names are provided
127 for compatibility with older or more exotic implementations.
128
129 @menu
130 * Generic Program Information::
131 * Matching Control::
132 * General Output Control::
133 * Output Line Prefix Control::
134 * Context Line Control::
135 * File and Directory Selection::
136 * Other Options::
137 @end menu
138
139 Several additional options control
140 which variant of the @command{grep} matching engine is used.
141 @xref{grep Programs}.
142
143 @node Generic Program Information
144 @subsection Generic Program Information
145
146 @table @samp
147
148 @item --help
149 @opindex --help
150 @cindex usage summary, printing
151 Print a usage message briefly summarizing the command-line options
152 and the bug-reporting address, then exit.
153
154 @item -V
155 @itemx --version
156 @opindex -V
157 @opindex --version
158 @cindex version, printing
159 Print the version number of @command{grep} to the standard output stream.
160 This version number should be included in all bug reports.
161
162 @end table
163
164 @node Matching Control
165 @subsection Matching Control
166
167 @table @samp
168
169 @item -e @var{pattern}
170 @itemx --regexp=@var{pattern}
171 @opindex -e
172 @opindex --regexp=@var{pattern}
173 @cindex pattern list
174 Use @var{pattern} as the pattern.
175 This can be used to specify multiple search patterns,
176 or to protect a pattern beginning with a @samp{-}.
177 (@samp{-e} is specified by @sc{posix}.)
178
179 @item -f @var{file}
180 @itemx --file=@var{file}
181 @opindex -f
182 @opindex --file
183 @cindex pattern from file
184 Obtain patterns from @var{file}, one per line.
185 The empty file contains zero patterns, and therefore matches nothing.
186 (@samp{-f} is specified by @sc{posix}.)
187
188 @item -i
189 @itemx -y
190 @itemx --ignore-case
191 @opindex -i
192 @opindex -y
193 @opindex --ignore-case
194 @cindex case insensitive search
195 Ignore case distinctions in both the pattern and the input files.
196 @samp{-y} is an obsolete synonym that is provided for compatibility.
197 (@samp{-i} is specified by @sc{posix}.)
198
199 @item -v
200 @itemx --invert-match
201 @opindex -v
202 @opindex --invert-match
203 @cindex invert matching
204 @cindex print non-matching lines
205 Invert the sense of matching, to select non-matching lines.
206 (@samp{-v} is specified by @sc{posix}.)
207
208 @item -w
209 @itemx --word-regexp
210 @opindex -w
211 @opindex --word-regexp
212 @cindex matching whole words
213 Select only those lines containing matches that form whole words.
214 The test is that the matching substring must either
215 be at the beginning of the line,
216 or preceded by a non-word constituent character.
217 Similarly,
218 it must be either at the end of the line
219 or followed by a non-word constituent character.
220 Word-constituent characters are letters, digits, and the underscore.
221
222 @item -x
223 @itemx --line-regexp
224 @opindex -x
225 @opindex --line-regexp
226 @cindex match the whole line
227 Select only those matches that exactly match the whole line.
228 (@samp{-x} is specified by @sc{posix}.)
229
230 @end table
231
232 @node General Output Control
233 @subsection General Output Control
234
235 @table @samp
236
237 @item -c
238 @itemx --count
239 @opindex -c
240 @opindex --count
241 @cindex counting lines
242 Suppress normal output;
243 instead print a count of matching lines for each input file.
244 With the @samp{-v}, @samp{--invert-match} option,
245 count non-matching lines.
246 (@samp{-c} is specified by @sc{posix}.)
247
248 @item --color[=@var{WHEN}]
249 @itemx --colour[=@var{WHEN}]
250 @opindex --color
251 @opindex --colour
252 @cindex highlight, color, colour
253 Surround the matched (non-empty) strings, matching lines, context lines,
254 file names, line numbers, byte offsets, and separators (for fields and
255 groups of context lines) with escape sequences to display them in color
256 on the terminal.
257 The colors are defined by the environment variable @var{GREP_COLORS}
258 and default to @samp{ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=32:bn=32:se=36}
259 for bold red matched text, magenta file names, green line numbers,
260 green byte offsets, cyan separators, and default terminal colors otherwise.
261 The deprecated environment variable @var{GREP_COLOR} is still supported,
262 but its setting does not have priority;
263 it defaults to `01;31' (bold red)
264 which only covers the color for matched text.
265 @var{WHEN} is @samp{never}, @samp{always}, or @samp{auto}.
266
267 @item -L
268 @itemx --files-without-match
269 @opindex -L
270 @opindex --files-without-match
271 @cindex files which don't match
272 Suppress normal output;
273 instead print the name of each input file from which
274 no output would normally have been printed.
275 The scanning of every file will stop on the first match.
276
277 @item -l
278 @itemx --files-with-matches
279 @opindex -l
280 @opindex --files-with-matches
281 @cindex names of matching files
282 Suppress normal output;
283 instead print the name of each input file from which
284 output would normally have been printed.
285 The scanning of every file will stop on the first match.
286 (@samp{-l} is specified by @sc{posix}.)
287
288 @item -m @var{num}
289 @itemx --max-count=@var{num}
290 @opindex -m
291 @opindex --max-count
292 @cindex max-count
293 Stop reading a file after @var{num} matching lines.
294 If the input is standard input from a regular file,
295 and @var{num} matching lines are output,
296 @command{grep} ensures that the standard input is positioned
297 just after the last matching line before exiting,
298 regardless of the presence of trailing context lines.
299 This enables a calling process to resume a search.
300 For example, the following shell script makes use of it:
301
302 @example
303 while grep -m 1 PATTERN
304 do
305   echo xxxx
306 done < FILE
307 @end example
308
309 But the following probably will not work because a pipe is not a regular
310 file:
311
312 @example
313 # This probably will not work.
314 cat FILE |
315 while grep -m 1 PATTERN
316 do
317   echo xxxx
318 done
319 @end example
320
321 When @command{grep} stops after @var{num} matching lines,
322 it outputs any trailing context lines.
323 Since context does not include matching lines,
324 @command{grep} will stop when it encounters another matching line.
325 When the @samp{-c} or @samp{--count} option is also used,
326 @command{grep} does not output a count greater than @var{num}.
327 When the @samp{-v} or @samp{--invert-match} option is also used,
328 @command{grep} stops after outputting @var{num} non-matching lines.
329
330 @item -o
331 @itemx --only-matching
332 @opindex -o
333 @opindex --only-matching
334 @cindex only matching
335 Print only the matched (non-empty) parts of matching lines,
336 with each such part on a separate output line.
337
338 @item -q
339 @itemx --quiet
340 @itemx --silent
341 @opindex -q
342 @opindex --quiet
343 @opindex --silent
344 @cindex quiet, silent
345 Quiet; do not write anything to standard output.
346 Exit immediately with zero status if any match is found,
347 even if an error was detected.
348 Also see the @samp{-s} or @samp{--no-messages} option.
349 (@samp{-q} is specified by @sc{posix}.)
350
351 @item -s
352 @itemx --no-messages
353 @opindex -s
354 @opindex --no-messages
355 @cindex suppress error messages
356 Suppress error messages about nonexistent or unreadable files.
357 Portability note:
358 unlike @sc{gnu} @command{grep},
359 7th Edition Unix @command{grep} did not conform to @sc{posix},
360 because it lacked @samp{-q}
361 and its @samp{-s} option behaved like
362 @sc{gnu} @command{grep}'s @samp{-q} option.
363 @sc{usg}-style @command{grep} also lacked @samp{-q}
364 but its @samp{-s} option behaved like @sc{gnu} @command{grep}'s.
365 Portable shell scripts should avoid both
366 @samp{-q} and @samp{-s} and should redirect
367 standard and error output to @file{/dev/null} instead.
368 (@samp{-s} is specified by @sc{posix}.)
369
370 @end table
371
372 @node Output Line Prefix Control
373 @subsection Output Line Prefix Control
374
375 When several prefix fields are to be output,
376 the order is always file name, line number, and byte offset,
377 regardless of the order in which these options were specified.
378
379 @table @samp
380
381 @item -b
382 @itemx --byte-offset
383 @opindex -b
384 @opindex --byte-offset
385 @cindex byte offset
386 Print the 0-based byte offset within the input file
387 before each line of output.
388 If @samp{-o} (@samp{--only-matching}) is specified,
389 print the offset of the matching part itself.
390 When @command{grep} runs on @sc{ms-dos} or @sc{ms}-Windows,
391 the printed byte offsets depend on whether
392 the @samp{-u} (@samp{--unix-byte-offsets}) option is used;
393 see below.
394
395 @item -H
396 @itemx --with-filename
397 @opindex -H
398 @opindex --with-filename
399 @cindex with filename prefix
400 Print the file name for each match.
401 This is the default when there is more than one file to search.
402
403 @item -h
404 @itemx --no-filename
405 @opindex -h
406 @opindex --no-filename
407 @cindex no filename prefix
408 Suppress the prefixing of file names on output.
409 This is the default when there is only one file
410 (or only standard input) to search.
411
412 @item --label=@var{LABEL}
413 @opindex --label
414 @cindex changing name of standard input
415 Display input actually coming from standard input
416 as input coming from file @var{LABEL}.  This is
417 especially useful when implementing tools like
418 @command{zgrep}; e.g.:
419
420 @example
421 gzip -cd foo.gz | grep --label=foo -H something
422 @end example
423
424 @item -n
425 @itemx --line-number
426 @opindex -n
427 @opindex --line-number
428 @cindex line numbering
429 Prefix each line of output with the 1-based line number within its input file.
430 (@samp{-n} is specified by @sc{posix}.)
431
432 @item -T
433 @itemx --initial-tab
434 @opindex -T
435 @opindex --initial-tab
436 @cindex tab-aligned content lines
437 Make sure that the first character of actual line content lies on a tab stop,
438 so that the alignment of tabs looks normal.
439 This is useful with options that prefix their output to the actual content:
440 @samp{-H}, @samp{-n}, and @samp{-b}.
441 In order to improve the probability that lines
442 from a single file will all start at the same column,
443 this also causes the line number and byte offset (if present)
444 to be printed in a minimum-size field width.
445
446 @item -u
447 @itemx --unix-byte-offsets
448 @opindex -u
449 @opindex --unix-byte-offsets
450 @cindex @sc{ms-dos}/@sc{ms}-Windows byte offsets
451 @cindex byte offsets, on @sc{ms-dos}/@sc{ms}-Windows
452 Report Unix-style byte offsets.
453 This option causes @command{grep} to report byte offsets
454 as if the file were a Unix-style text file,
455 i.e., the byte offsets ignore the @code{CR} characters that were stripped.
456 This will produce results identical
457 to running @command{grep} on a Unix machine.
458 This option has no effect unless the @samp{-b} option is also used;
459 it has no effect on platforms other than @sc{ms-dos} and @sc{ms}-Windows.
460
461 @item -Z
462 @itemx --null
463 @opindex -Z
464 @opindex --null
465 @cindex zero-terminated file names
466 Output a zero byte (the @sc{ascii} @code{NUL} character)
467 instead of the character that normally follows a file name.
468 For example,
469 @samp{grep -lZ} outputs a zero byte after each file name
470 instead of the usual newline.
471 This option makes the output unambiguous,
472 even in the presence of file names containing unusual characters like newlines.
473 This option can be used with commands like
474 @samp{find -print0}, @samp{perl -0}, @samp{sort -z}, and @samp{xargs -0}
475 to process arbitrary file names,
476 even those that contain newline characters.
477
478 @end table
479
480 @node Context Line Control
481 @subsection Context Line Control
482
483 Regardless of how these options are set,
484 @command{grep} will never print any given line more than once.
485 If the @samp{-o} or @samp{--only-matching} option is specified,
486 these options have no effect and a warning is given upon their use.
487
488 @table @samp
489
490 @item -A @var{num}
491 @itemx --after-context=@var{num}
492 @opindex -A
493 @opindex --after-context
494 @cindex after context
495 @cindex context lines, after match
496 Print @var{num} lines of trailing context after matching lines.
497
498 @item -B @var{num}
499 @itemx --before-context=@var{num}
500 @opindex -B
501 @opindex --before-context
502 @cindex before context
503 @cindex context lines, before match
504 Print @var{num} lines of leading context before matching lines.
505
506 @item -C @var{num}
507 @itemx -@var{num}
508 @itemx --context=@var{num}
509 @opindex -C
510 @opindex --context
511 @opindex -@var{num}
512 @cindex context
513 Print @var{num} lines of leading and trailing output context.
514
515 @item --group-separator=@var{string}
516 @opindex --group-separator
517 @cindex group separator
518 When @option{-A}, @option{-B} or @option{-C} are in use,
519 print @var{string} instead of @samp{--} around disjoint groups
520 of lines.
521
522 @item --no-group-separator
523 @opindex --group-separator
524 @cindex group separator
525 When @option{-A}, @option{-B} or @option{-C} are in use,
526 print disjoint groups of lines adjacent to each other.
527
528 @end table
529
530 Matching lines normally use @samp{:} as a separator
531 between prefix fields and actual line content.
532 Context (i.e., non-matching) lines use @samp{-} instead.
533 When no context is specified,
534 matching lines are simply output one right after another.
535 When nonzero context is specified,
536 lines that are adjacent in the input form a group
537 and are output one right after another, while
538 a separator appears by default between disjoint groups on a line
539 of its own and without any prefix.  The default separator
540 is @samp{--}, however whether to include it and its appearance
541 can be changed with the options above.  Each group may contain
542 several matching lines when they are close enough to each other
543 that two otherwise adjacent but divided groups connect
544 and can just merge into a single contiguous one.
545
546 @node File and Directory Selection
547 @subsection File and Directory Selection
548
549 @table @samp
550
551 @item -a
552 @itemx --text
553 @opindex -a
554 @opindex --text
555 @cindex suppress binary data
556 @cindex binary files
557 Process a binary file as if it were text;
558 this is equivalent to the @samp{--binary-files=text} option.
559
560 @itemx --binary-files=@var{type}
561 @opindex --binary-files
562 @cindex binary files
563 If the first few bytes of a file indicate that the file contains binary data,
564 assume that the file is of type @var{type}.
565 By default, @var{type} is @samp{binary},
566 and @command{grep} normally outputs either
567 a one-line message saying that a binary file matches,
568 or no message if there is no match.
569 If @var{type} is @samp{without-match},
570 @command{grep} assumes that a binary file does not match;
571 this is equivalent to the @samp{-I} option.
572 If @var{type} is @samp{text},
573 @command{grep} processes a binary file as if it were text;
574 this is equivalent to the @samp{-a} option.
575 @emph{Warning:} @samp{--binary-files=text} might output binary garbage,
576 which can have nasty side effects
577 if the output is a terminal and
578 if the terminal driver interprets some of it as commands.
579
580 @item -D @var{action}
581 @itemx --devices=@var{action}
582 @opindex -D
583 @opindex --devices
584 @cindex device search
585 If an input file is a device, FIFO, or socket, use @var{action} to process it.
586 By default, @var{action} is @samp{read},
587 which means that devices are read just as if they were ordinary files.
588 If @var{action} is @samp{skip},
589 devices, FIFOs, and sockets are silently skipped.
590
591 @item -d @var{action}
592 @itemx --directories=@var{action}
593 @opindex -d
594 @opindex --directories
595 @cindex directory search
596 If an input file is a directory, use @var{action} to process it.
597 By default, @var{action} is @samp{read},
598 which means that directories are read just as if they were ordinary files
599 (some operating systems and file systems disallow this,
600 and will cause @command{grep}
601 to print error messages for every directory or silently skip them).
602 If @var{action} is @samp{skip}, directories are silently skipped.
603 If @var{action} is @samp{recurse},
604 @command{grep} reads all files under each directory, recursively;
605 this is equivalent to the @samp{-r} option.
606
607 @item --exclude=@var{glob}
608 @opindex --exclude
609 @cindex exclude files
610 @cindex searching directory trees
611 Skip files whose base name matches @var{glob}
612 (using wildcard matching).
613 A file-name glob can use
614 @samp{*}, @samp{?}, and @samp{[}...@samp{]} as wildcards,
615 and @code{\} to quote a wildcard or backslash character literally.
616
617 @item --exclude-from=@var{file}
618 @opindex --exclude-from
619 @cindex exclude files
620 @cindex searching directory trees
621 Skip files whose base name matches any of the file-name globs
622 read from @var{file} (using wildcard matching as described
623 under @samp{--exclude}).
624
625 @item --exclude-dir=@var{dir}
626 @opindex --exclude-dir
627 @cindex exclude directories
628 Exclude directories matching the pattern @var{dir} from recursive
629 directory searches.
630
631 @item -I
632 Process a binary file as if it did not contain matching data;
633 this is equivalent to the @samp{--binary-files=without-match} option.
634
635 @item --include=@var{glob}
636 @opindex --include
637 @cindex include files
638 @cindex searching directory trees
639 Search only files whose base name matches @var{glob}
640 (using wildcard matching as described under @samp{--exclude}).
641
642 @item -r
643 @itemx -R
644 @itemx --recursive
645 @opindex -r
646 @opindex --recursive
647 @cindex recursive search
648 @cindex searching directory trees
649 For each directory mentioned on the command line,
650 read and process all files in that directory, recursively.
651 This is the same as the @samp{--directories=recurse} option.
652
653 @end table
654
655 @node Other Options
656 @subsection Other Options
657
658 @table @samp
659
660 @item --line-buffered
661 @opindex --line-buffered
662 @cindex line buffering
663 Use line buffering on output.
664 This can cause a performance penalty.
665
666 @item --mmap
667 @opindex --mmap
668 @cindex memory mapped input
669 This option is ignored for backwards compatibility.  It used to read
670 input with the @code{mmap} system call, instead of the default @code{read}
671 system call.  On modern systems, @code{mmap} would rarely if ever yield
672 better performance.
673
674 @item -U
675 @itemx --binary
676 @opindex -U
677 @opindex --binary
678 @cindex @sc{ms-dos}/@sc{ms}-Windows binary files
679 @cindex binary files, @sc{ms-dos}/@sc{ms}-Windows
680 Treat the file(s) as binary.
681 By default, under @sc{ms-dos} and @sc{ms}-Windows,
682 @command{grep} guesses the file type
683 by looking at the contents of the first 32kB read from the file.
684 If @command{grep} decides the file is a text file,
685 it strips the @code{CR} characters from the original file contents
686 (to make regular expressions with @code{^} and @code{$} work correctly).
687 Specifying @samp{-U} overrules this guesswork,
688 causing all files to be read and passed to the matching mechanism verbatim;
689 if the file is a text file with @code{CR/LF} pairs at the end of each line,
690 this will cause some regular expressions to fail.
691 This option has no effect
692 on platforms other than @sc{ms-dos} and @sc{ms}-Windows.
693
694 @item -z
695 @itemx --null-data
696 @opindex -z
697 @opindex --null-data
698 @cindex zero-terminated lines
699 Treat the input as a set of lines, each terminated by a zero byte (the
700 @sc{ascii} @code{NUL} character) instead of a newline.
701 Like the @samp{-Z} or @samp{--null} option,
702 this option can be used with commands like
703 @samp{sort -z} to process arbitrary file names.
704
705 @end table
706
707 @node Environment Variables
708 @section Environment Variables
709
710 The behavior of @command{grep} is affected
711 by the following environment variables.
712
713 The locale for category @w{@code{LC_@var{foo}}}
714 is specified by examining the three environment variables
715 @env{LC_ALL}, @w{@env{LC_@var{foo}}}, and @env{LANG},
716 in that order.
717 The first of these variables that is set specifies the locale.
718 For example, if @env{LC_ALL} is not set,
719 but @env{LC_MESSAGES} is set to @samp{pt_BR},
720 then the Brazilian Portuguese locale is used
721 for the @code{LC_MESSAGES} category.
722 The @samp{C} locale is used if none of these environment variables are set,
723 if the locale catalog is not installed,
724 or if @command{grep} was not compiled
725 with national language support (@sc{nls}).
726
727 @cindex environment variables
728
729 @table @env
730
731 @item GREP_OPTIONS
732 @vindex GREP_OPTIONS @r{environment variable}
733 @cindex default options environment variable
734 This variable specifies default options to be placed in front of any
735 explicit options.
736 For example, if @code{GREP_OPTIONS} is
737 @samp{--binary-files=without-match --directories=skip}, @command{grep}
738 behaves as if the two options @samp{--binary-files=without-match} and
739 @samp{--directories=skip} had been specified before
740 any explicit options.
741 Option specifications are separated by
742 whitespace.
743 A backslash escapes the next character, so it can be used to
744 specify an option containing whitespace or a backslash.
745
746 @item GREP_COLOR
747 @vindex GREP_COLOR @r{environment variable}
748 @cindex highlight markers
749 This variable specifies the color used to highlight matched (non-empty) text.
750 It is deprecated in favor of @code{GREP_COLORS}, but still supported.
751 The @samp{mt}, @samp{ms}, and @samp{mc} capabilities of @code{GREP_COLORS}
752 have priority over it.
753 It can only specify the color used to highlight
754 the matching non-empty text in any matching line
755 (a selected line when the @samp{-v} command-line option is omitted,
756 or a context line when @samp{-v} is specified).
757 The default is @samp{01;31},
758 which means a bold red foreground text on the terminal's default background.
759
760 @item GREP_COLORS
761 @vindex GREP_COLORS @r{environment variable}
762 @cindex highlight markers
763 This variable specifies the colors and other attributes
764 used to highlight various parts of the output.
765 Its value is a colon-separated list of capabilities
766 that defaults to @samp{ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=32:bn=32:se=36}
767 with the @samp{rv} and @samp{ne} boolean capabilities omitted (i.e., false).
768 Supported capabilities are as follows.
769
770 @table @code
771 @item sl=
772 @vindex sl GREP_COLORS @r{capability}
773 SGR substring for whole selected lines
774 (i.e.,
775 matching lines when the @samp{-v} command-line option is omitted,
776 or non-matching lines when @samp{-v} is specified).
777 If however the boolean @samp{rv} capability
778 and the @samp{-v} command-line option are both specified,
779 it applies to context matching lines instead.
780 The default is empty (i.e., the terminal's default color pair).
781
782 @item cx=
783 @vindex cx GREP_COLORS @r{capability}
784 SGR substring for whole context lines
785 (i.e.,
786 non-matching lines when the @samp{-v} command-line option is omitted,
787 or matching lines when @samp{-v} is specified).
788 If however the boolean @samp{rv} capability
789 and the @samp{-v} command-line option are both specified,
790 it applies to selected non-matching lines instead.
791 The default is empty (i.e., the terminal's default color pair).
792
793 @item rv
794 @vindex rv GREP_COLORS @r{capability}
795 Boolean value that reverses (swaps) the meanings of
796 the @samp{sl=} and @samp{cx=} capabilities
797 when the @samp{-v} command-line option is specified.
798 The default is false (i.e., the capability is omitted).
799
800 @item mt=01;31
801 @vindex mt GREP_COLORS @r{capability}
802 SGR substring for matching non-empty text in any matching line
803 (i.e.,
804 a selected line when the @samp{-v} command-line option is omitted,
805 or a context line when @samp{-v} is specified).
806 Setting this is equivalent to setting both @samp{ms=} and @samp{mc=}
807 at once to the same value.
808 The default is a bold red text foreground over the current line background.
809
810 @item ms=01;31
811 @vindex ms GREP_COLORS @r{capability}
812 SGR substring for matching non-empty text in a selected line.
813 (This is only used when the @samp{-v} command-line option is omitted.)
814 The effect of the @samp{sl=} (or @samp{cx=} if @samp{rv}) capability
815 remains active when this kicks in.
816 The default is a bold red text foreground over the current line background.
817
818 @item mc=01;31
819 @vindex mc GREP_COLORS @r{capability}
820 SGR substring for matching non-empty text in a context line.
821 (This is only used when the @samp{-v} command-line option is specified.)
822 The effect of the @samp{cx=} (or @samp{sl=} if @samp{rv}) capability
823 remains active when this kicks in.
824 The default is a bold red text foreground over the current line background.
825
826 @item fn=35
827 @vindex fn GREP_COLORS @r{capability}
828 SGR substring for file names prefixing any content line.
829 The default is a magenta text foreground over the terminal's default background.
830
831 @item ln=32
832 @vindex ln GREP_COLORS @r{capability}
833 SGR substring for line numbers prefixing any content line.
834 The default is a green text foreground over the terminal's default background.
835
836 @item bn=32
837 @vindex bn GREP_COLORS @r{capability}
838 SGR substring for byte offsets prefixing any content line.
839 The default is a green text foreground over the terminal's default background.
840
841 @item se=36
842 @vindex fn GREP_COLORS @r{capability}
843 SGR substring for separators that are inserted
844 between selected line fields (@samp{:}),
845 between context line fields (@samp{-}),
846 and between groups of adjacent lines
847 when nonzero context is specified (@samp{--}).
848 The default is a cyan text foreground over the terminal's default background.
849
850 @item ne
851 @vindex ne GREP_COLORS @r{capability}
852 Boolean value that prevents clearing to the end of line
853 using Erase in Line (EL) to Right (@samp{\33[K})
854 each time a colorized item ends.
855 This is needed on terminals on which EL is not supported.
856 It is otherwise useful on terminals
857 for which the @code{back_color_erase}
858 (@code{bce}) boolean terminfo capability does not apply,
859 when the chosen highlight colors do not affect the background,
860 or when EL is too slow or causes too much flicker.
861 The default is false (i.e., the capability is omitted).
862 @end table
863
864 Note that boolean capabilities have no @samp{=}... part.
865 They are omitted (i.e., false) by default and become true when specified.
866
867 See the Select Graphic Rendition (SGR) section
868 in the documentation of your text terminal
869 for permitted values and their meaning as character attributes.
870 These substring values are integers in decimal representation
871 and can be concatenated with semicolons.
872 @command{grep} takes care of assembling the result
873 into a complete SGR sequence (@samp{\33[}...@samp{m}).
874 Common values to concatenate include
875 @samp{1} for bold,
876 @samp{4} for underline,
877 @samp{5} for blink,
878 @samp{7} for inverse,
879 @samp{39} for default foreground color,
880 @samp{30} to @samp{37} for foreground colors,
881 @samp{90} to @samp{97} for 16-color mode foreground colors,
882 @samp{38;5;0} to @samp{38;5;255}
883 for 88-color and 256-color modes foreground colors,
884 @samp{49} for default background color,
885 @samp{40} to @samp{47} for background colors,
886 @samp{100} to @samp{107} for 16-color mode background colors,
887 and @samp{48;5;0} to @samp{48;5;255}
888 for 88-color and 256-color modes background colors.
889
890 @item LC_ALL
891 @itemx LC_COLLATE
892 @itemx LANG
893 @vindex LC_ALL @r{environment variable}
894 @vindex LC_COLLATE @r{environment variable}
895 @vindex LANG @r{environment variable}
896 @cindex character type
897 @cindex national language support
898 @cindex NLS
899 These variables specify the locale for the @code{LC_COLLATE} category,
900 which determines the collating sequence
901 used to interpret range expressions like @samp{[a-z]}.
902
903 @item LC_ALL
904 @itemx LC_CTYPE
905 @itemx LANG
906 @vindex LC_ALL @r{environment variable}
907 @vindex LC_CTYPE @r{environment variable}
908 @vindex LANG @r{environment variable}
909 These variables specify the locale for the @code{LC_CTYPE} category,
910 which determines the type of characters,
911 e.g., which characters are whitespace.
912
913 @item LC_ALL
914 @itemx LC_MESSAGES
915 @itemx LANG
916 @vindex LC_ALL @r{environment variable}
917 @vindex LC_MESSAGES @r{environment variable}
918 @vindex LANG @r{environment variable}
919 @cindex language of messages
920 @cindex message language
921 @cindex national language support
922 @cindex translation of message language
923 These variables specify the locale for the @code{LC_MESSAGES} category,
924 which determines the language that @command{grep} uses for messages.
925 The default @samp{C} locale uses American English messages.
926
927 @item POSIXLY_CORRECT
928 @vindex POSIXLY_CORRECT @r{environment variable}
929 If set, @command{grep} behaves as @sc{posix.2} requires; otherwise,
930 @command{grep} behaves more like other @sc{gnu} programs.
931 @sc{posix.2}
932 requires that options that
933 follow file names must be treated as file names;
934 by default,
935 such options are permuted to the front of the operand list
936 and are treated as options.
937 Also, @code{POSIXLY_CORRECT} disables special handling of an
938 invalid bracket expression.  @xref{invalid-bracket-expr}.
939
940 @item _@var{N}_GNU_nonoption_argv_flags_
941 @vindex _@var{N}_GNU_nonoption_argv_flags_ @r{environment variable}
942 (Here @code{@var{N}} is @command{grep}'s numeric process ID.)
943 If the @var{i}th character of this environment variable's value is @samp{1},
944 do not consider the @var{i}th operand of @command{grep} to be an option,
945 even if it appears to be one.
946 A shell can put this variable in the environment for each command it runs,
947 specifying which operands are the results of file name wildcard expansion
948 and therefore should not be treated as options.
949 This behavior is available only with the @sc{gnu} C library,
950 and only when @code{POSIXLY_CORRECT} is not set.
951
952 @end table
953
954
955 @node Exit Status
956 @section Exit Status
957 @cindex exit status
958 @cindex return status
959
960 Normally, the exit status is 0 if selected lines are found and 1 otherwise.
961 But the exit status is 2 if an error occurred, unless the @option{-q} or
962 @option{--quiet} or @option{--silent} option is used and a selected line
963 is found.
964 Note, however, that @sc{posix} only mandates,
965 for programs such as @command{grep}, @command{cmp}, and @command{diff},
966 that the exit status in case of error be greater than 1;
967 it is therefore advisable, for the sake of portability,
968 to use logic that tests for this general condition
969 instead of strict equality with@ 2.
970
971
972 @node grep Programs
973 @section @command{grep} Programs
974 @cindex @command{grep} programs
975 @cindex variants of @command{gerp}
976
977 @command{grep} searches the named input files
978 (or standard input if no files are named,
979 or the file name @file{-} is given)
980 for lines containing a match to the given pattern.
981 By default, @command{grep} prints the matching lines.
982 There are four major variants of @command{grep},
983 controlled by the following options.
984
985 @table @samp
986
987 @item -G
988 @itemx --basic-regexp
989 @opindex -G
990 @opindex --basic-regexp
991 @cindex matching basic regular expressions
992 Interpret the pattern as a basic regular expression (BRE).
993 This is the default.
994
995 @item -E
996 @itemx --extended-regexp
997 @opindex -E
998 @opindex --extended-regexp
999 @cindex matching extended regular expressions
1000 Interpret the pattern as an extended regular expression (ERE).
1001 (@samp{-E} is specified by @sc{posix}.)
1002
1003 @item -F
1004 @itemx --fixed-strings
1005 @opindex -F
1006 @opindex --fixed-strings
1007 @cindex matching fixed strings
1008 Interpret the pattern as a list of fixed strings, separated
1009 by newlines, any of which is to be matched.
1010 (@samp{-F} is specified by @sc{posix}.)
1011
1012 @item -P
1013 @itemx --perl-regexp
1014 @opindex -P
1015 @opindex --perl-regexp
1016 @cindex matching Perl regular expressions
1017 Interpret the pattern as a Perl regular expression.
1018 This is highly experimental and
1019 @samp{grep@ -P} may warn of unimplemented features.
1020
1021 @end table
1022
1023 In addition,
1024 two variant programs @command{egrep} and @command{fgrep} are available.
1025 @command{egrep} is the same as @samp{grep@ -E}.
1026 @command{fgrep} is the same as @samp{grep@ -F}.
1027 Direct invocation as either
1028 @command{egrep} or @command{fgrep} is deprecated,
1029 but is provided to allow historical applications
1030 that rely on them to run unmodified.
1031
1032
1033 @node Regular Expressions
1034 @chapter Regular Expressions
1035 @cindex regular expressions
1036
1037 A @dfn{regular expression} is a pattern that describes a set of strings.
1038 Regular expressions are constructed analogously to arithmetic expressions,
1039 by using various operators to combine smaller expressions.
1040 @command{grep} understands
1041 three different versions of regular expression syntax:
1042 ``basic,'' (BRE) ``extended'' (ERE) and ``perl''.
1043 In @sc{gnu} @command{grep},
1044 there is no difference in available functionality between basic and
1045 extended syntaxes.
1046 In other implementations, basic regular expressions are less powerful.
1047 The following description applies to extended regular expressions;
1048 differences for basic regular expressions are summarized afterwards.
1049 Perl regular expressions give additional functionality, and are
1050 documented in pcresyntax(3) and pcrepattern(3), but may not be
1051 available on every system.
1052
1053 @menu
1054 * Fundamental Structure::
1055 * Character Classes and Bracket Expressions::
1056 * The Backslash Character and Special Expressions::
1057 * Anchoring::
1058 * Back-references and Subexpressions::
1059 * Basic vs Extended::
1060 @end menu
1061
1062 @node Fundamental Structure
1063 @section Fundamental Structure
1064
1065 The fundamental building blocks are the regular expressions that match
1066 a single character.
1067 Most characters, including all letters and digits,
1068 are regular expressions that match themselves.
1069 Any meta-character
1070 with special meaning may be quoted by preceding it with a backslash.
1071
1072 A regular expression may be followed by one of several
1073 repetition operators:
1074
1075 @table @samp
1076
1077 @item .
1078 @opindex .
1079 @cindex dot
1080 @cindex period
1081 The period @samp{.} matches any single character.
1082
1083 @item ?
1084 @opindex ?
1085 @cindex question mark
1086 @cindex match expression at most once
1087 The preceding item is optional and will be matched at most once.
1088
1089 @item *
1090 @opindex *
1091 @cindex asterisk
1092 @cindex match expression zero or more times
1093 The preceding item will be matched zero or more times.
1094
1095 @item +
1096 @opindex +
1097 @cindex plus sign
1098 @cindex match expression one or more times
1099 The preceding item will be matched one or more times.
1100
1101 @item @{@var{n}@}
1102 @opindex @{@var{n}@}
1103 @cindex braces, one argument
1104 @cindex match expression @var{n} times
1105 The preceding item is matched exactly @var{n} times.
1106
1107 @item @{@var{n},@}
1108 @opindex @{@var{n},@}
1109 @cindex braces, second argument omitted
1110 @cindex match expression @var{n} or more times
1111 The preceding item is matched @var{n} or more times.
1112
1113 @item @{,@var{m}@}
1114 @opindex @{,@var{m}@}
1115 @cindex braces, first argument omitted
1116 @cindex match expression at most @var{m} times
1117 The preceding item is matched at most @var{m} times.
1118
1119 @item @{@var{n},@var{m}@}
1120 @opindex @{@var{n},@var{m}@}
1121 @cindex braces, two arguments
1122 @cindex match expression from @var{n} to @var{m} times
1123 The preceding item is matched at least @var{n} times, but not more than
1124 @var{m} times.
1125
1126 @end table
1127
1128 Two regular expressions may be concatenated;
1129 the resulting regular expression
1130 matches any string formed by concatenating two substrings
1131 that respectively match the concatenated expressions.
1132
1133 Two regular expressions may be joined by the infix operator @samp{|};
1134 the resulting regular expression
1135 matches any string matching either alternalte expression.
1136
1137 Repetition takes precedence over concatenation,
1138 which in turn takes precedence over alternation.
1139 A whole expression may be enclosed in parentheses
1140 to override these precedence rules and form a subexpression.
1141
1142 @node Character Classes and Bracket Expressions
1143 @section Character Classes and Bracket Expressions
1144
1145 @cindex bracket expression
1146 @cindex character class
1147 A @dfn{bracket expression} is a list of characters enclosed by @samp{[} and
1148 @samp{]}.
1149 It matches any single character in that list;
1150 if the first character of the list is the caret @samp{^},
1151 then it matches any character @strong{not} in the list.
1152 For example, the regular expression
1153 @samp{[0123456789]} matches any single digit.
1154
1155 @cindex range expression
1156 Within a bracket expression, a @dfn{range expression} consists of two
1157 characters separated by a hyphen.
1158 It matches any single character that
1159 sorts between the two characters, inclusive, using the locale's
1160 collating sequence and character set.
1161 For example, in the default C
1162 locale, @samp{[a-d]} is equivalent to @samp{[abcd]}.
1163 Many locales sort
1164 characters in dictionary order, and in these locales @samp{[a-d]} is
1165 typically not equivalent to @samp{[abcd]};
1166 it might be equivalent to @samp{[aBbCcDd]}, for example.
1167 To obtain the traditional interpretation
1168 of bracket expressions, you can use the @samp{C} locale by setting the
1169 @env{LC_ALL} environment variable to the value @samp{C}.
1170
1171 Finally, certain named classes of characters are predefined within
1172 bracket expressions, as follows.
1173 Their interpretation depends on the @code{LC_CTYPE} locale;
1174 the interpretation below is that of the @samp{C} locale,
1175 which is the default if no @code{LC_CTYPE} locale is specified.
1176
1177 @cindex classes of characters
1178 @cindex character classes
1179 @table @samp
1180
1181 @item [:alnum:]
1182 @opindex alnum @r{character class}
1183 @cindex alphanumeric characters
1184 Alphanumeric characters:
1185 @samp{[:alpha:]} and @samp{[:digit:]}.
1186
1187 @item [:alpha:]
1188 @opindex alpha @r{character class}
1189 @cindex alphabetic characters
1190 Alphabetic characters:
1191 @samp{[:lower:]} and @samp{[:upper:]}.
1192
1193 @item [:blank:]
1194 @opindex blank @r{character class}
1195 @cindex blank characters
1196 Blank characters:
1197 space and tab.
1198
1199 @item [:cntrl:]
1200 @opindex cntrl @r{character class}
1201 @cindex control characters
1202 Control characters.
1203 In @sc{ascii}, these characters have octal codes 000
1204 through 037, and 177 (@code{DEL}).
1205 In other character sets, these are
1206 the equivalent characters, if any.
1207
1208 @item [:digit:]
1209 @opindex digit @r{character class}
1210 @cindex digit characters
1211 @cindex numeric characters
1212 Digits: @code{0 1 2 3 4 5 6 7 8 9}.
1213
1214 @item [:graph:]
1215 @opindex graph @r{character class}
1216 @cindex graphic characters
1217 Graphical characters:
1218 @samp{[:alnum:]} and @samp{[:punct:]}.
1219
1220 @item [:lower:]
1221 @opindex lower @r{character class}
1222 @cindex lower-case letters
1223 Lower-case letters:
1224 @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}.
1225
1226 @item [:print:]
1227 @opindex print @r{character class}
1228 @cindex printable characters
1229 Printable characters:
1230 @samp{[:alnum:]}, @samp{[:punct:]}, and space.
1231
1232 @item [:punct:]
1233 @opindex punct @r{character class}
1234 @cindex punctuation characters
1235 Punctuation characters:
1236 @code{!@: " # $ % & ' ( ) * + , - .@: / : ; < = > ?@: @@ [ \ ] ^ _ ` @{ | @} ~}.
1237
1238 @item [:space:]
1239 @opindex space @r{character class}
1240 @cindex space characters
1241 @cindex whitespace characters
1242 Space characters:
1243 tab, newline, vertical tab, form feed, carriage return, and space.
1244 @xref{Usage}, for more discussion of matching newlines.
1245
1246 @item [:upper:]
1247 @opindex upper @r{character class}
1248 @cindex upper-case letters
1249 Upper-case letters:
1250 @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}.
1251
1252 @item [:xdigit:]
1253 @opindex xdigit @r{character class}
1254 @cindex xdigit class
1255 @cindex hexadecimal digits
1256 Hexadecimal digits:
1257 @code{0 1 2 3 4 5 6 7 8 9 A B C D E F a b c d e f}.
1258
1259 @end table
1260 For example, @samp{[[:alnum:]]} means @samp{[0-9A-Za-z]}, except the latter
1261 depends upon the @samp{C} locale and the @sc{ascii} character
1262 encoding, whereas the former is independent of locale and character set.
1263 (Note that the brackets in these class names are
1264 part of the symbolic names, and must be included in addition to
1265 the brackets delimiting the bracket expression.)
1266
1267 @anchor{invalid-bracket-expr}
1268 If you mistakenly omit the outer brackets, and search for say, @samp{[:upper:]},
1269 GNU @command{grep} prints a diagnostic and exits with status 2, on
1270 the assumption that you did not intend to search for the nominally
1271 equivalent regular expression: @samp{[:epru]}.
1272 Set the @code{POSIXLY_CORRECT} environment variable to disable this feature.
1273
1274 Most meta-characters lose their special meaning inside bracket expressions.
1275
1276 @table @samp
1277 @item ]
1278 ends the bracket expression if it's not the first list item.
1279 So, if you want to make the @samp{]} character a list item,
1280 you must put it first.
1281
1282 @item [.
1283 represents the open collating symbol.
1284
1285 @item .]
1286 represents the close collating symbol.
1287
1288 @item [=
1289 represents the open equivalence class.
1290
1291 @item =]
1292 represents the close equivalence class.
1293
1294 @item [:
1295 represents the open character class symbol, and should be followed by a valid character class name.
1296
1297 @item :]
1298 represents the close character class symbol.
1299
1300 @item -
1301 represents the range if it's not first or last in a list or the ending point
1302 of a range.
1303
1304 @item ^
1305 represents the characters not in the list.
1306 If you want to make the @samp{^}
1307 character a list item, place it anywhere but first.
1308
1309 @end table
1310
1311 @node The Backslash Character and Special Expressions
1312 @section The Backslash Character and Special Expressions
1313 @cindex backslash
1314
1315 The @samp{\} character,
1316 when followed by certain ordinary characters,
1317 takes a special meaning:
1318
1319 @table @samp
1320
1321 @item @samp{\b}
1322 Match the empty string at the edge of a word.
1323
1324 @item @samp{\B}
1325 Match the empty string provided it's not at the edge of a word.
1326
1327 @item @samp{\<}
1328 Match the empty string at the beginning of word.
1329
1330 @item @samp{\>}
1331 Match the empty string at the end of word.
1332
1333 @item @samp{\w}
1334 Match word constituent, it is a synonym for @samp{[[:alnum:]]}.
1335
1336 @item @samp{\W}
1337 Match non-word constituent, it is a synonym for @samp{[^[:alnum:]]}.
1338
1339 @item @samp{\s}
1340 Match whitespace, it is a synonym for @samp{[[:space:]]}.
1341
1342 @item @samp{\S}
1343 Match non-whitespace, it is a synonym for @samp{[^[:space:]]}.
1344
1345 @end table
1346
1347 For example, @samp{\brat\b} matches the separate word @samp{rat},
1348 @samp{\Brat\B} matches @samp{crate} but not @samp{furry rat}.
1349
1350 @node Anchoring
1351 @section Anchoring
1352 @cindex anchoring
1353
1354 The caret @samp{^} and the dollar sign @samp{$} are meta-characters that
1355 respectively match the empty string at the beginning and end of a line.
1356
1357 @node Back-references and Subexpressions
1358 @section Back-references and Subexpressions
1359 @cindex subexpression
1360 @cindex back-reference
1361
1362 The back-reference @samp{\@var{n}}, where @var{n} is a single digit, matches
1363 the substring previously matched by the @var{n}th parenthesized subexpression
1364 of the regular expression.
1365 For example, @samp{(a)\1} matches @samp{aa}.
1366 When used with alternation, if the group does not participate in the match then
1367 the back-reference makes the whole match fail.
1368 For example, @samp{a(.)|b\1}
1369 will not match @samp{ba}.
1370 When multiple regular expressions are given with
1371 @samp{-e} or from a file (@samp{-f file}),
1372 back-references are local to each expression.
1373
1374 @node Basic vs Extended
1375 @section Basic vs Extended Regular Expressions
1376 @cindex basic regular expressions
1377
1378 In basic regular expressions the meta-characters @samp{?}, @samp{+},
1379 @samp{@{}, @samp{|}, @samp{(}, and @samp{)} lose their special meaning;
1380 instead use the backslashed versions @samp{\?}, @samp{\+}, @samp{\@{},
1381 @samp{\|}, @samp{\(}, and @samp{\)}.
1382
1383 @cindex interval specifications
1384 Traditional @command{egrep} did not support the @samp{@{} meta-character,
1385 and some @command{egrep} implementations support @samp{\@{} instead, so
1386 portable scripts should avoid @samp{@{} in @samp{grep@ -E} patterns and
1387 should use @samp{[@{]} to match a literal @samp{@{}.
1388
1389 @sc{gnu} @command{grep@ -E} attempts to support traditional usage by
1390 assuming that @samp{@{} is not special if it would be the start of an
1391 invalid interval specification.
1392 For example, the command
1393 @samp{grep@ -E@ '@{1'} searches for the two-character string @samp{@{1}
1394 instead of reporting a syntax error in the regular expression.
1395 @sc{posix.2} allows this behavior as an extension, but portable scripts
1396 should avoid it.
1397
1398
1399 @node Usage
1400 @chapter Usage
1401
1402 @cindex usage, examples
1403 Here is an example command that invokes @sc{gnu} @command{grep}:
1404
1405 @example
1406 grep -i 'hello.*world' menu.h main.c
1407 @end example
1408
1409 @noindent
1410 This lists all lines in the files @file{menu.h} and @file{main.c} that
1411 contain the string @samp{hello} followed by the string @samp{world};
1412 this is because @samp{.*} matches zero or more characters within a line.
1413 @xref{Regular Expressions}.
1414 The @samp{-i} option causes @command{grep}
1415 to ignore case, causing it to match the line @samp{Hello, world!}, which
1416 it would not otherwise match.
1417 @xref{Invoking}, for more details about
1418 how to invoke @command{grep}.
1419
1420 @cindex using @command{grep}, Q&A
1421 @cindex FAQ about @command{grep} usage
1422 Here are some common questions and answers about @command{grep} usage.
1423
1424 @enumerate
1425
1426 @item
1427 How can I list just the names of matching files?
1428
1429 @example
1430 grep -l 'main' *.c
1431 @end example
1432
1433 @noindent
1434 lists the names of all C files in the current directory whose contents
1435 mention @samp{main}.
1436
1437 @item
1438 How do I search directories recursively?
1439
1440 @example
1441 grep -r 'hello' /home/gigi
1442 @end example
1443
1444 @noindent
1445 searches for @samp{hello} in all files
1446 under the @file{/home/gigi} directory.
1447 For more control over which files are searched,
1448 use @command{find}, @command{grep}, and @command{xargs}.
1449 For example, the following command searches only C files:
1450
1451 @example
1452 find /home/gigi -name '*.c' -print0 | xargs -0r grep -H 'hello'
1453 @end example
1454
1455 This differs from the command:
1456
1457 @example
1458 grep -rH 'hello' *.c
1459 @end example
1460
1461 which merely looks for @samp{hello} in all files in the current
1462 directory whose names end in @samp{.c}.
1463 Here the @option{-r} is
1464 probably unnecessary, as recursion occurs only in the unlikely event
1465 that one of @samp{.c} files is a directory.
1466 The @samp{find ...} command line above is more similar to the command:
1467
1468 @example
1469 grep -rH --include='*.c' 'hello' /home/gigi
1470 @end example
1471
1472 @item
1473 What if a pattern has a leading @samp{-}?
1474
1475 @example
1476 grep -e '--cut here--' *
1477 @end example
1478
1479 @noindent
1480 searches for all lines matching @samp{--cut here--}.
1481 Without @samp{-e},
1482 @command{grep} would attempt to parse @samp{--cut here--} as a list of
1483 options.
1484
1485 @item
1486 Suppose I want to search for a whole word, not a part of a word?
1487
1488 @example
1489 grep -w 'hello' *
1490 @end example
1491
1492 @noindent
1493 searches only for instances of @samp{hello} that are entire words;
1494 it does not match @samp{Othello}.
1495 For more control, use @samp{\<} and
1496 @samp{\>} to match the start and end of words.
1497 For example:
1498
1499 @example
1500 grep 'hello\>' *
1501 @end example
1502
1503 @noindent
1504 searches only for words ending in @samp{hello}, so it matches the word
1505 @samp{Othello}.
1506
1507 @item
1508 How do I output context around the matching lines?
1509
1510 @example
1511 grep -C 2 'hello' *
1512 @end example
1513
1514 @noindent
1515 prints two lines of context around each matching line.
1516
1517 @item
1518 How do I force @command{grep} to print the name of the file?
1519
1520 Append @file{/dev/null}:
1521
1522 @example
1523 grep 'eli' /etc/passwd /dev/null
1524 @end example
1525
1526 gets you:
1527
1528 @example
1529 /etc/passwd:eli:x:2098:1000:Eli Smith:/home/eli:/bin/bash
1530 @end example
1531
1532 Alternatively, use @samp{-H}, which is a @sc{gnu} extension:
1533
1534 @example
1535 grep -H 'eli' /etc/passwd
1536 @end example
1537
1538 @item
1539 Why do people use strange regular expressions on @command{ps} output?
1540
1541 @example
1542 ps -ef | grep '[c]ron'
1543 @end example
1544
1545 If the pattern had been written without the square brackets, it would
1546 have matched not only the @command{ps} output line for @command{cron},
1547 but also the @command{ps} output line for @command{grep}.
1548 Note that on some platforms,
1549 @command{ps} limits the output to the width of the screen;
1550 @command{grep} does not have any limit on the length of a line
1551 except the available memory.
1552
1553 @item
1554 Why does @command{grep} report ``Binary file matches''?
1555
1556 If @command{grep} listed all matching ``lines'' from a binary file, it
1557 would probably generate output that is not useful, and it might even
1558 muck up your display.
1559 So @sc{gnu} @command{grep} suppresses output from
1560 files that appear to be binary files.
1561 To force @sc{gnu} @command{grep}
1562 to output lines even from files that appear to be binary, use the
1563 @samp{-a} or @samp{--binary-files=text} option.
1564 To eliminate the
1565 ``Binary file matches'' messages, use the @samp{-I} or
1566 @samp{--binary-files=without-match} option.
1567
1568 @item
1569 Why doesn't @samp{grep -lv} print non-matching file names?
1570
1571 @samp{grep -lv} lists the names of all files containing one or more
1572 lines that do not match.
1573 To list the names of all files that contain no
1574 matching lines, use the @samp{-L} or @samp{--files-without-match}
1575 option.
1576
1577 @item
1578 I can do @sc{or} with @samp{|}, but what about @sc{and}?
1579
1580 @example
1581 grep 'paul' /etc/motd | grep 'franc,ois'
1582 @end example
1583
1584 @noindent
1585 finds all lines that contain both @samp{paul} and @samp{franc,ois}.
1586
1587 @item
1588 How can I search in both standard input and in files?
1589
1590 Use the special file name @samp{-}:
1591
1592 @example
1593 cat /etc/passwd | grep 'alain' - /etc/motd
1594 @end example
1595
1596 @item
1597 @cindex palindromes
1598 How to express palindromes in a regular expression?
1599
1600 It can be done by using back-references;
1601 for example,
1602 a palindrome of 4 characters can be written with a BRE:
1603
1604 @example
1605 grep -w -e '\(.\)\(.\).\2\1' file
1606 @end example
1607
1608 It matches the word "radar" or "civic".
1609
1610 Guglielmo Bondioni proposed a single RE
1611 that finds all palindromes up to 19 characters long
1612 using @w{9 subexpressions} and @w{9 back-references}:
1613
1614 @smallexample
1615 grep -E -e '^(.?)(.?)(.?)(.?)(.?)(.?)(.?)(.?)(.?).?\9\8\7\6\5\4\3\2\1$' file
1616 @end smallexample
1617
1618 Note this is done by using @sc{gnu} ERE extensions;
1619 it might not be portable to other implementations of @command{grep}.
1620
1621 @item
1622 Why is this back-reference failing?
1623
1624 @example
1625 echo 'ba' | grep -E '(a)\1|b\1'
1626 @end example
1627
1628 This gives no output, because the first alternate @samp{(a)\1} does not match,
1629 as there is no @samp{aa} in the input, so the @samp{\1} in the second alternate
1630 has nothing to refer back to, meaning it will never match anything.
1631 (The second alternate in this example can only match
1632 if the first alternate has matched---making the second one superfluous.)
1633
1634 @item
1635 How can I match across lines?
1636
1637 Standard grep cannot do this, as it is fundamentally line-based.
1638 Therefore, merely using the @code{[:space:]} character class does not
1639 match newlines in the way you might expect.  However, if your grep is
1640 compiled with Perl patterns enabled, the Perl @samp{s}
1641 modifier (which makes @code{.} match newlines) can be used:
1642
1643 @example
1644 printf 'foo\nbar\n' | grep -P '(?s)foo.*?bar'
1645 @end example
1646
1647 With the GNU @command{grep} option @code{-z} (@pxref{File and
1648 Directory Selection}), the input is terminated by null bytes.  Thus,
1649 you can match newlines in the input, but the output will be the whole
1650 file, so this is really only useful to determine if the pattern is
1651 present:
1652
1653 @example
1654 printf 'foo\nbar\n' | grep -z -q 'foo[[:space:]]\+bar'
1655 @end example
1656
1657 Failing either of those options, you need to transform the input
1658 before giving it to @command{grep}, or turn to @command{awk},
1659 @command{sed}, @command{perl}, or many other utilities that are
1660 designed to operate across lines.
1661
1662 @item
1663 What do @command{grep}, @command{fgrep}, and @command{egrep} stand for?
1664
1665 The name @command{grep} comes from the way line editing was done on Unix.
1666 For example,
1667 @command{ed} uses the following syntax
1668 to print a list of matching lines on the screen:
1669
1670 @example
1671 global/regular expression/print
1672 g/re/p
1673 @end example
1674
1675 @command{fgrep} stands for Fixed @command{grep};
1676 @command{egrep} stands for Extended @command{grep}.
1677
1678 @end enumerate
1679
1680
1681 @node Reporting Bugs
1682 @chapter Reporting bugs
1683
1684 @cindex bugs, reporting
1685 Email bug reports to @email{bug-grep@@gnu.org},
1686 a mailing list whose web page is
1687 @url{http://lists.gnu.org/mailman/listinfo/bug-grep}.
1688 The Savannah bug tracker for @command{grep} is located at
1689 @url{http://savannah.gnu.org/bugs/?group=grep}.
1690
1691 @section Known Bugs
1692 @cindex Bugs, known
1693
1694 Large repetition counts in the @samp{@{n,m@}} construct may cause
1695 @command{grep} to use lots of memory.
1696 In addition, certain other
1697 obscure regular expressions require exponential time and
1698 space, and may cause @command{grep} to run out of memory.
1699
1700 Back-references are very slow, and may require exponential time.
1701
1702
1703 @node Copying
1704 @chapter Copying
1705 @cindex copying
1706
1707 GNU grep is licensed under the GNU GPL, which makes it @dfn{free
1708 software}.
1709
1710 The ``free'' in ``free software'' refers to liberty, not price. As
1711 some GNU project advocates like to point out, think of ``free speech''
1712 rather than ``free beer''.  In short, you have the right (freedom) to
1713 run and change grep and distribute it to other people, and---if you
1714 want---charge money for doing either.  The important restriction is
1715 that you have to grant your recipients the same rights and impose the
1716 same restrictions.
1717
1718 This general method of licensing software is sometimes called
1719 @dfn{open source}.  The GNU project prefers the term ``free software''
1720 for reasons outlined at
1721 @url{http://www.gnu.org/philosophy/open-source-misses-the-point.html}.
1722
1723 This manual is free documentation in the same sense.  The
1724 documentation license is included below.  The license for the program
1725 is available with the source code, or at
1726 @url{http://www.gnu.org/licenses/gpl.html}.
1727
1728 @menu
1729 * GNU Free Documentation License::
1730 @end menu
1731
1732 @node GNU Free Documentation License
1733 @section GNU Free Documentation License
1734
1735 @include fdl.texi
1736
1737
1738 @node Index
1739 @unnumbered Index
1740
1741 @printindex cp
1742
1743 @bye