Glam Prestige Journal

Bright entertainment trends with youth appeal.

. means match any character in regular expressions.* means zero or more occurrences of the SINGLE regex preceding it. My alphabet.txt contains a line

abcdefghijklmnopqrstuvwxyz

Doesn't grep a.*z alphabet.txt mean match any substrings that start with a, with zero or more occurrences of any type of SINGLE character in between them, and end with z? For example, abz, abbz, ahhhhhz, but not abbdz?

I thought grep a.*z alphabet.txt wouldn't catch the line in my alphabet file.

4 Answers

* means that the immediately-preceding pattern is repeated, not that the matched text is repeated. For example, [ab]* means (|[ab]|[ab][ab]|[ab][ab][ab]|…) The pattern [ab] is repeated zero or more times. It will match "aba" because that properly fulfills the pattern [ab][ab][ab].

With .*, it becomes (|.|..|...|....|…), so it matches any number of characters, and the characters can differ.

In abbdz, just because . matched b at first doesn't mean . will only match b for the rest of the expression.

Repetition modifiers such as * act on the preceding regex atom, not on repeats of the character matched by the preceding regex atom. So for example:

$ printf 'az\nabz\nabbz\nabbbz\nabcz\n' | sed -n '/a.*z/p'
az
abz
abbz
abbbz
abcz

(all lines match). If you want to only match repeats of the matched character, you can use a backreference:

$ printf 'az\nabz\nabbz\nabbbz\nabcz\n' | sed -n '/a\(.\)\1*z/p'
abz
abbz
abbbz
4

grep a.*z matches everything between the first occurrence of a and the last occurrence of z, including the first a and the last z. The .* is a wildcard expression that matches any sequence of characters including an empty sequence of length=0. grep a.*z matches all of the following strings that start with a and end with z: "abcdefghijklmnopqrstuvwxyz", "abz", "abbz", "ahhhhhz" and "abbdz". It also matches text that spans multiple lines, for example this text:

abcdefghijklmnopqrstuvwxyz
abz
abbz
ahhhhhz
abbdz

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy