Geavanceerd
Zoeken inSamenvattingen
Zo zoek je
  • Woorden vinden lestitels, tekst en code. Filter op soort (gidsen, cursussen, programma's, boeken) of blijf in dit boek.
  • book:rhcsa en ch:8 maken de zoektocht kleiner; #code vindt een woord alleen in commando's van de lessen.
  • "twee woorden" vindt precies die zin.
  • Gewone woorden vinden namen, teksten en voorbeelden.
  • ↑ ↓ bewegen · Enter openen · Esc sluiten · / zoeken
Probeer:

Hoofdstuk 19Naam in het boek: Regular Expressions

Regular expressions

A regular expression (regex) is a pattern that describes text. grep, sed, awk, less, vim, find and almost every programming language use them. This chapter teaches the regex language step by step with grep: literals, the dot, anchors, bracket expressions, classes, alternation and quantifiers.

  • 12 Lessen
  • 11 Commando's
  • 1 Labs

Dit deel is nog niet vertaald. Je ziet de Engelse tekst.

$ als gewone gebruiker# als root (of met sudo)

Vaardigheden in dit hoofdstuk

  • Reguliere expressies schrijven voor grep, sed, find en vim

19.1

Know what a regex is

A regex is a small language for patterns. It is like wildcards, but much more powerful, and the rules are a bit different.

  • POSIX (the Unix standard) defines two kinds: basic (BRE) and extended (ERE).
  • Other tools (Perl, Python, JavaScript) use bigger dialects, but the basics are the same.

19.2

Search with grep

grep ("global regular expression print") prints the lines that match a regex.

OptionWhat it does
-iIgnore upper / lower case
-vPrint the lines that do not match
-cPrint only the number of matching lines
-l / -LPrint only the names of files with / without a match
-nPut the line number in front
-hNo file names in front (with many files)
-oPrint only the matching part
-rSearch all files in a directory tree
-EExtended regex (same as egrep)
-FFixed text, no regex (fast)
-wMatch whole words only
ls /bin > dirlist-bin.txt
ls /usr/bin > dirlist-usr-bin.txt
grep bzip dirlist*.txt
dirlist-bin.txt:bzip2
dirlist-usr-bin.txt:bzip2
grep -l bzip dirlist*.txt
grep -c zip dirlist-usr-bin.txt
grep -rn "Listen" /etc/httpd/

19.3

Use literals and metacharacters

Most characters match themselves (literals). A few have a special meaning (metacharacters).

the metacharacters
^ $ . [ ] { } - ? * + ( ) | \
  • In basic regex, ?, +, { }, ( ) and | are literals unless you escape them with \. In extended regex (grep -E) they are special.
  • To match a metacharacter as a literal, escape it: \. matches a real dot.

Let op

Always put a regex in quotes on the command line: grep -E 'a|b' file. Many metacharacters also mean something to the shell.

Commando's in deze les

19.4

Match any character with the dot

. matches exactly one character, whatever it is.

grep -h '.zip' dirlist*.txt
bunzip2
bzip2
funzip
gunzip
gzip
unzip

zip itself is not in the list: .zip needs one character before zip.

19.5

Use anchors

^ matches the start of a line, $ the end of a line.

grep -h '^zip' dirlist*.txt
grep -h 'zip$' dirlist*.txt
grep -h '^zip$' dirlist*.txt
zip
grep -c '^$' /etc/services
grep -v '^#' /etc/ssh/sshd_config | grep -v '^$'

Op het werk

grep -v '^#' file | grep -v '^$' shows a config file without comments and empty lines: only the real settings.

Commando's in deze les

19.6

Solve a crossword with a regex

Combine the dot and anchors to search a word list, for example "5 letters, 3rd is j, last is r".

grep -i '^..j.r$' /usr/share/dict/words
Major
major

Commando's in deze les

19.7

Use bracket expressions

[abc] matches one character from a set. [^abc] matches one character not in the set. - makes a range.

grep -h '[bg]zip' dirlist*.txt
bzip2
gzip
grep -h '[^bg]zip' dirlist*.txt
grep -h '^[A-Z]' dirlist*.txt
grep -h '^[A-Za-z0-9]' dirlist*.txt
grep -h '[-AZ]' dirlist*.txt
  • Inside brackets most metacharacters are literals. Only ^ (at the start, negation) and - (range) are special.
  • To match a - itself, put it first: [-AZ].

Commando's in deze les

19.8

Use POSIX character classes

Ranges like [A-Z] depend on the language setting. Classes like [:upper:] always work. Note the double brackets: [[:upper:]].

ClassMatches
[:alnum:]Letters and digits
[:alpha:]Letters
[:blank:]Space and tab
[:cntrl:]Control characters
[:digit:]Digits 0–9
[:lower:] / [:upper:]Small / capital letters
[:punct:]Punctuation
[:space:]Space, tab, new line and other white space
[:xdigit:]Hexadecimal digits
ls /usr/sbin/[[:upper:]]*
grep -h '^[[:upper:]]' dirlist*.txt

Notitie

With a UTF-8 language, the old ranges may follow dictionary order (aAbB…). export LANG=POSIX gives the old ASCII order back, but the classes are the clean solution.

19.9

Use alternation and groups

| means "or" (extended regex). Parentheses group parts of the pattern.

echo "AAA" | grep -E 'AAA|BBB'
AAA
grep -Eh '^(bz|gz|zip)' dirlist*.txt
grep -Eh '^bz|gz|zip' dirlist*.txt

The last two are different: ^(bz|gz|zip) = starts with one of them; ^bz|gz|zip = starts with bz, or contains gz, or contains zip.

19.10

Use quantifiers

Quantifiers say how many times the element before them may appear.

QuantifierMeans
?0 or 1 time
*0 or more times
+1 or more times
{n}exactly n times
{n,m}n to m times
{n,}n or more times
{,m}at most m times
echo "(555) 123-4567" | grep -E '^\(?[0-9][0-9][0-9]\)? [0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]$'
(555) 123-4567
echo "This works." | grep -E '[[:upper:]][[:upper:][:lower:] ]*\.'
This works.
echo "This that" | grep -E '^([[:alpha:]]+ ?)+$'
This that
echo "555 123-4567" | grep -E '^\(?[0-9]{3}\)? [0-9]{3}-[0-9]{4}$'
555 123-4567

19.11

Put regex to work

The same patterns work in many tools: check data with grep, find bad file names with find -regex, search with locate --regex, less and vim.

grep -Ev '^\([0-9]{3}\) [0-9]{3}-[0-9]{4}$' phonelist.txt
find . -regex '.*[^-_./0-9a-zA-Z].*'
locate --regex 'bin/(bz|gz|zip)'
grep -Eo '[0-9]{1,3}(\.[0-9]{1,3}){3}' /var/log/secure | sort | uniq -c | sort -rn | head
  • grep -Ev with a valid pattern shows the invalid lines of a list.
  • find -regex matches the whole path, so the pattern starts with .*.
  • In less and vim, / searches with a regex. In vim, /\v turns on "very magic" mode (like extended regex).

Op het werk

The last example counts the IP addresses in a log file: a quick way to see who tries to log in.

19.12

Summary of the chapter

. any, ^ $ anchors, [ ] sets, [[:class:]], | or, ? * + { } counts. Use grep -E for extended regex.

1Which regex matches lines that are exactly "zip"?

^zip$.

2What is the difference between [^0-9] and ^[0-9]?

[^0-9] = one character that is not a digit; ^[0-9] = a digit at the start of the line.

3Which grep option is needed for +, ?, | and { } without backslashes?

-E (extended regex).

Oefenen

Alle commando's in dit hoofdstuk