Shell programming basics-regular expressions

Regular expression

Match the included text string (regular is the relationship of inclusion, as long as it is included, it will match)

  • Basic regular expression: load via grep
  • Extended regular expression: through egrep or grep -E

grep -v negate

Basic regular expression

  • n* (asterisk): match n that contains the previous character, match 0 times or any number of times (if there is a character before the asterisk, match 0 times means match all, all of the text)
  • . (Dot): match contains any one character (except newline characters)
  • ^: match the first line
  • $: match the last line
  • [] (Brackets): match any character in the brackets, the range is 1-9 (one horizontal)
  • [^] (Inside brackets + angle sign): reverse, different from outside square brackets + angle sign ^ []
  • \: Cancel the meaning of special characters and become ordinary characters
  • {n}: n occurrences of the preceding character
  • {n,}: The preceding character appears more than or equal to n times
  • {n,m}: The preceding character appears more than n times and less than m times

When using grep -E, the last three \ do not add backslash {n,m}

Extended regular expression

  • +: The previous symbol matches one or more times
  • ? : The previous symbol matches 0 or 1 time
  • |: Or the relationship
  • (): represents a whole character

Practice questions:

1. Display the lines starting with capital S and A in the /proc/meminfo file

egrep "^(A|S)" /proc/meminfo

2. Display the lines that do not end with /bin/bash in the /etc/passwd file

grep -v "/bin/bash$" /etc/passwd

3. Display the 4 users starting with s in the /etc/passwd file

grep "^s...:" /etc/passwd

4. Display lines with spaces in the /etc/passwd file (not case sensitive)

grep -i "[0-9a-z] [0-9a-z]" /etc/passwd

5. Display blank lines in the /etc/passwd file

grep "^$" /etc/passwd

6. Display the two-digit or three-digit number in the /etc/passwd file

egrep "[0-9]{2,3}" /etc/passwd

Guess you like

Origin blog.csdn.net/yangshihuz/article/details/110946451