2013-12-08 19:56:16 +11:00
|
|
|
# grep
|
|
|
|
|
2021-03-28 10:22:29 -04:00
|
|
|
> Find patterns in files using regular expressions.
|
2021-04-18 00:08:17 +02:00
|
|
|
> More information: <https://www.gnu.org/software/grep/manual/grep.html>.
|
2013-12-08 19:56:16 +11:00
|
|
|
|
2020-06-09 10:34:03 +02:00
|
|
|
- Search for a pattern within a file:
|
2015-10-22 15:31:52 +08:00
|
|
|
|
2021-03-28 10:22:29 -04:00
|
|
|
`grep "{{search_pattern}}" {{path/to/file}}`
|
2013-12-08 19:56:16 +11:00
|
|
|
|
2021-03-28 10:22:29 -04:00
|
|
|
- Search for an exact string (disables regular expressions):
|
2016-01-28 00:12:10 +02:00
|
|
|
|
2024-06-06 21:04:35 +02:00
|
|
|
`grep {{-F|--fixed-strings}} "{{exact_string}}" {{path/to/file}}`
|
2016-01-28 00:12:10 +02:00
|
|
|
|
2021-03-28 10:22:29 -04:00
|
|
|
- Search for a pattern in all files recursively in a directory, showing line numbers of matches, ignoring binary files:
|
2014-01-28 13:41:32 +01:00
|
|
|
|
2024-06-06 21:04:35 +02:00
|
|
|
`grep {{-r|--recursive}} {{-n|--line-number}} --binary-files {{without-match}} "{{search_pattern}}" {{path/to/directory}}`
|
2014-01-28 13:41:32 +01:00
|
|
|
|
2025-01-15 04:56:32 +07:00
|
|
|
- Use extended regular expressions (supports `?`, `+`, `{}`, `()`, and `|`), in case-insensitive mode:
|
2013-12-08 19:56:16 +11:00
|
|
|
|
2024-06-06 21:04:35 +02:00
|
|
|
`grep {{-E|--extended-regexp}} {{-i|--ignore-case}} "{{search_pattern}}" {{path/to/file}}`
|
2013-12-08 19:56:16 +11:00
|
|
|
|
2021-03-28 10:22:29 -04:00
|
|
|
- Print 3 lines of context around, before, or after each match:
|
2013-12-08 19:56:16 +11:00
|
|
|
|
2024-06-19 06:16:49 +02:00
|
|
|
`grep --{{context|before-context|after-context}} 3 "{{search_pattern}}" {{path/to/file}}`
|
2013-12-08 19:56:16 +11:00
|
|
|
|
2022-05-14 02:26:00 +08:00
|
|
|
- Print file name and line number for each match with color output:
|
2013-12-08 19:56:16 +11:00
|
|
|
|
2024-06-06 21:04:35 +02:00
|
|
|
`grep {{-H|--with-filename}} {{-n|--line-number}} --color=always "{{search_pattern}}" {{path/to/file}}`
|
2016-06-21 15:11:27 +08:00
|
|
|
|
2021-03-28 10:22:29 -04:00
|
|
|
- Search for lines matching a pattern, printing only the matched text:
|
2013-12-08 19:56:16 +11:00
|
|
|
|
2024-06-06 21:04:35 +02:00
|
|
|
`grep {{-o|--only-matching}} "{{search_pattern}}" {{path/to/file}}`
|
2014-07-27 10:23:56 +02:00
|
|
|
|
2022-12-04 08:53:34 +01:00
|
|
|
- Search `stdin` for lines that do not match a pattern:
|
2014-07-27 10:23:56 +02:00
|
|
|
|
2024-06-06 21:04:35 +02:00
|
|
|
`cat {{path/to/file}} | grep {{-v|--invert-match}} "{{search_pattern}}"`
|