Linux Labs

Bash: text processing and scripts / Stage 1 of 9

Regular expressions in grep

Not running Starting usually ~20 s
Leave the lesson

Step 4 of 6 · on a machine · 7 min

Cutting out the match

Sometimes you need one piece of a line: an error number, an address, a name. Here is a pattern for such a piece and an option that prints only it.

In extended syntax, + after a character or a set means "one or more in a row". [0-9]+ is a number of any length, and err=[0-9]+ matches err=0, err=5 and err=12. A number in curly braces sets an exact count of repeats: [0-9]{3} is three digits in a row. The -o option changes what grep prints — see how.

Exercise · look

Cut out the error numbers

In ~/grep-lab, search for err= with a number using the -o option, then count what it finds with a pipeline.

First, predict

What will the first command, with the -o option, print?

Now start the exercise, run the command and compare your prediction with the output.

Sign in and start The machine is available after signing in

With -o, grep prints each match on a line of its own, without the rest of the text. Such output is ready input for sort | uniq -c from the pipelines lesson: the count shows which error number comes up most often.

A dot in a pattern is any character, so the pattern 10.0.0.7 also matches 10a0b0c7. To make a dot stand for itself, put a backslash before it: 10\.0\.0\.7.

Check yourself 1 question

hosts.txt has three lines: 192.168.1.1 gw, 192.168.111.5 printer and 192.168.1.10 nas. Which of them will grep '192.168.1.1' hosts.txt print?

  • A dot matches any character, so the pattern was found in 192.168.111.5 too. And in 192.168.1.10 it matched the start of the address.

  • In 192.168.1.10 the pattern matched the first eleven characters: grep looks for it anywhere in a line, so the nas line is in the output too.

  • A dot in a pattern is any character: in 192.168.111.5 it matched the digit 1, so the printer line is in the output too.

The dot matched a digit in the printer's address, and in the nas address the pattern was found at the start of a longer number. Only the gw line comes out of grep -w '192\.168\.1\.1' hosts.txt: escaped dots and a whole word.

Ubuntu 24.04
Loading…