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
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.
Search with grep
grep ("global regular expression print") prints the lines that match a regex.
| Option | What it does |
|---|---|
-i | Ignore upper / lower case |
-v | Print the lines that do not match |
-c | Print only the number of matching lines |
-l / -L | Print only the names of files with / without a match |
-n | Put the line number in front |
-h | No file names in front (with many files) |
-o | Print only the matching part |
-r | Search all files in a directory tree |
-E | Extended regex (same as egrep) |
-F | Fixed text, no regex (fast) |
-w | Match whole words only |
Use literals and metacharacters
Most characters match themselves (literals). A few have a special meaning (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.
Match any character with the dot
. matches exactly one character, whatever it is.
Use anchors
^ matches the start of a line, $ the end of a line.
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
majorUse 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].
Use POSIX character classes
Ranges like [A-Z] depend on the language setting. Classes like [:upper:] always work. Note the double brackets: [[:upper:]].
| Class | Matches |
|---|---|
[: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 |
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.
Use alternation and groups
| means "or" (extended regex). Parentheses group parts of the pattern.
Use quantifiers
Quantifiers say how many times the element before them may appear.
| Quantifier | Means |
|---|---|
? | 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-4567Put 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 | headgrep -Evwith a valid pattern shows the invalid lines of a list.find -regexmatches the whole path, so the pattern starts with.*.- In
lessandvim,/searches with a regex. In vim,/\vturns 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.
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).