tldr/pages/common/grep.md

37 lines
1.3 KiB
Markdown
Raw Normal View History

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
- 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
2021-03-28 15:22:29 +01:00
`grep --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:
2021-03-28 15:22:29 +01:00
`grep --recursive --line-number --binary-files={{without-match}} "{{search_pattern}}" {{path/to/directory}}`
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
2021-03-28 15:22:29 +01:00
`grep --extended-regexp --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
2021-03-28 15:22:29 +01:00
`grep --{{context|before-context|after-context}}={{3}} "{{search_pattern}}" {{path/to/file}}`
2013-12-08 08:56:16 +00:00
- Print file name and line number for each match with color output:
2013-12-08 08:56:16 +00:00
`grep --with-filename --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
2021-03-28 15:22:29 +01:00
`grep --only-matching "{{search_pattern}}" {{path/to/file}}`
2014-07-27 09:23:56 +01:00
2021-03-28 15:22:29 +01:00
- Search stdin for lines that do not match a pattern:
2014-07-27 09:23:56 +01:00
2021-03-28 15:22:29 +01:00
`cat {{path/to/file}} | grep --invert-match "{{search_pattern}}"`