🎓 A1Learner
🔍
0 of 46 lessons completed

Bash Grep Perl Patterns

Perl grep patterns are search patterns that use short codes for digits, word parts, and spaces. The -P option turns on this Perl form in GNU grep, and it adds lookahead and lookbehind tests.

Short codes for digits, words, and spaces

The -o run prints only the digit groups 42 and 9. The anchored run finds the line that starts with a word and a number. The last run finds the line where code is followed by a space and a capital letter.

printf 'order 42 paid\ncall me now\ncode A9 done\n' > notes.txt
grep -P -o '\d+' notes.txt
grep -P '^\w+ \d+' notes.txt
grep -P 'code\s[A-Z]' notes.txt

Word boundaries stop partial matches

The boundary marks on both sides of cat demand a whole word. The lines with cats and concatenate fail, so only the two true cat lines print.

printf 'cat\ncats\nconcatenate\ncat food\n' > pets.txt
grep -P '\bcat\b' pets.txt

Lookahead checks what follows

The pattern takes digits only when dollars follows them. The euros price fails the lookahead, so its number stays hidden.

printf 'price 50 dollars\nprice 80 euros\nprice 30 dollars\n' > prices.txt
grep -P -o '\d+(?= dollars)' prices.txt

Lookbehind checks what comes before

The pattern takes digits only when id: and a space come before them. The ref line fails the lookbehind, so its number stays hidden.

printf 'id: 101 done\nid: 202 done\nref: 303 done\n' > ids.txt
grep -P -o '(?<=id: )\d+' ids.txt

Example

printf 'order ORD-991 total 120 dollars\norder ORD-992 total 75 euros\norder ORD-993 total 200 dollars\n' > orders.txt
grep -P -o '(?<=ORD-)\d+' orders.txt
grep -P -o '\d+(?= dollars)' orders.txt

Key points

  • -P: turns on Perl patterns in GNU grep.
  • GNU only: -P works with GNU grep and may fail on other systems.
  • \d: matches one digit.
  • \w: matches one word character, a letter, digit, or underscore.
  • \s: matches one blank space or tab.
  • Lookahead: (?=...) checks what follows without including it in the match.
  • Lookbehind: (?<=...) checks what comes before without including it in the match.
  • Word boundary: \b marks the edge between a word character and other text.

In this example, the script first creates a small order list. The lookbehind run prints each order number that follows ORD-. The lookahead run prints only the totals that sit before dollars, so the euros total stays hidden.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which grep -P pattern extracts only the number after 'id: '?