跳转到正文

Using Grep & Regular Expressions

From Using Grep & Regular Expressions to Search for Text Patterns in Linux

Linux

From Using Grep & Regular Expressions to Search for Text Patterns in Linux

Basic Usage

$ grep [Pattern] [Input File]

Print out every line in the file containing that Pattern

Common OptionsDescription
-i == --ignore-caseboth upper- and lower-case variations
-v == --invert-matchdo not contain the Pattern
-n == --line-numbershow the line number

A Little bit about Regular Expressions

Anchor Matches

Anchor MatchesDescription
^at the begining of the string(line)
$at the end of the string

Matching Any Character

Any CharacterDescription
.match any single character

Bracket Expressions

  • Characters between [ and ] means OR
  • But if the characters start with ^, it means NOT, i.e. except
  • Represent a range of characters: [A-Z], but we can use POSIX character classes to replace the [A-Z]: [[:upper:]]

Repeat Pattern Zero or More Times

CharacterDescription
*repeat the previous character or expression zero or more times

Escaping Meta-Characters

Using backslash character \ to escape characters that would normally have a special meaning.

Extended Regular Expressions

Use -E flag or call egrep command to use Extended Regular Expressions

Groupinn

Alternation

Quantifiers

CharacterDescription
?match the previouscharacter zero or one times
+one or more times

Specifying Match Repetition

{NUM} to specify matching times, from an exact number, a range, or an upper or lower bounds