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