Grep: Difference between revisions

From wikinotes
No edit summary
 
Line 34: Line 34:
only available in gnu grep via <code>-P</code>, this supports lookahead/lookbehind.
only available in gnu grep via <code>-P</code>, this supports lookahead/lookbehind.


match lines
<syntaxhighlight lang="bash">
<syntaxhighlight lang="bash">
xrandr | grep -P '(?<!dis)connected'  # negative lookbehind
xrandr | grep -P '(?<!dis)connected'  # negative lookbehind
xrandr | grep -P '(?<=dis)connected'  # positive lookehind
xrandr | grep -P '(?<=dis)connected'  # positive lookehind
</syntaxhighlight>
extract regex groups
<syntaxhighlight lang="bash">
xrandr | grep -P '\d+x\d+' -o          # extract resolutions(ex: 1920x1080) from every line in xrandr
</syntaxhighlight>
</syntaxhighlight>
</blockquote><!-- Perl  -->
</blockquote><!-- Perl  -->
</blockquote><!-- Regex -->
</blockquote><!-- Regex -->

Latest revision as of 02:08, 19 July 2021

Search file contents.

Documentation

man grep https://manpages.debian.org/buster/grep/grep.1.en.html

Usage

grep <dir> \
  -C3  `# show 3x lines before/after each match` \
  -l   `# show only matched files` \
  -i   `# case insensitive search` \
  -v   `# lines-not matching` \
  -E   `# extended regex` \
  -P   `# (gnu-only) perl extended regex (supports lookahead/behind)` \

multiline grep

grep -Pzo 'def[^\n]+\n\tfoo'

Regex

Perl

only available in gnu grep via -P, this supports lookahead/lookbehind.

match lines

xrandr | grep -P '(?<!dis)connected'   # negative lookbehind
xrandr | grep -P '(?<=dis)connected'   # positive lookehind

extract regex groups

xrandr | grep -P '\d+x\d+' -o          # extract resolutions(ex: 1920x1080) from every line in xrandr