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