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