Linux grep command

  

1. Function

The grep command in Linux is a powerful text search tool that can search for text using regular expressions and print the matching lines. The full name of grep is Global Regular Expression Print, which represents the global regular expression version, and its usage rights are for all users.

2. Format grep [options]

3. Main parameters

[options] Main parameters: -c: Output only the count of matching lines. -I: Does not distinguish between uppercase and lowercase (only for single characters). -h: Do not display the file name when querying multiple files. -l: When querying multiple files, only the file name containing the matching characters is output. -n: Display matching lines and line numbers. -s: Do not display error messages that do not exist or have no matching text. -v: Displays all lines that do not contain matching text.

The main parameters of the pattern regular expression: \\: Ignore the original meaning of special characters in the regular expression. ^: Matches the start line of the regular expression. $: matches the end line of the regular expression. \\<: Starts with a line that matches the regular expression. \\>: ends with a line that matches the regular expression. [ ]: A single character, such as [A] that A meets the requirements. [ - ]: Range, such as [A-Z], that is, A, B, C all the way to Z meet the requirements. .: All single characters. * : All characters can be 0 in length.

{n}: Must match n times. {n,}: Must match n times or more than n times. {n,m}: The number of matches is between n and m, including n and m.

4.Instances

1. Output the line number with "the" $grep -n 'the' a.txt

2. The output does not have "the" Line number $grep -nv 'the' a.txt

3. Use [] to search for collection elements, [] for any character, for example [abc] can mean a, b or c $grep -n 't[abc]ab' a.txt

You can use the ^ symbol to make a prefix in [], which means characters other than the characters in []. For example, if you search for a line with no g string before oo, use '[^g]oo' to do the search string $grep -n '[^g]oo' a.txt

[] can be used The range indicates, for example, [az] for lowercase characters, [0-9] for numbers 0-9, and [AZ] for uppercase letters. [a-zA-Z0-9] $grep -n 't[]ab' a.txt

4. Search for empty lines, use '^$' to indicate only empty lines at the beginning and end of the line $ Grep -n '^$' a.txt

5. Search for non-empty lines, use '^$' to indicate only empty lines at the beginning and end of the line $grep -nv '^$' a.txt< Br>

6. Search for a line containing two oos $grep -n 'o\\{\\2\\}' a.txt

7. Count the number containing "the" $grep - c 'the' a.txt

Copyright © Windows knowledge All Rights Reserved