user6420577
user6420577

Reputation: 225

regular expression character class with grep comamnd

I am learning regular expression past few days. i used to character class [] for range of selection only alpha characters in lower case only.

For example: file contain text like below:

$ cat file
.a
.b
.c .d

Using grep command i am trying to match (line starts with dot) lower case alphabetic characters using below command

$ grep '^\.[a-z]' file

this will matching characters only .a .b .c Here my question? why grep command not matching .d in the same line .c

I tried to match .d using this command also:

$ grep '^\.[a-z][a-z]` file 

But this one does not work can you please some one help me to this one ? and what is the difference between these two character class

[a-z] vs [a-z][a-z]

Upvotes: 1

Views: 512

Answers (1)

vallentin
vallentin

Reputation: 26197

If you want to match all of them, then remove ^, doing:

grep '\.[a-z]' file

The ^ means that it must be at the start of a line. So you're trying to match a literal dot, followed by a character in the range of a and z. Which must be at the start of a line.

The difference between [a-z] and [a-z][a-z] is thereby that [a-z] matches a single character in the range of a-z. Doing [a-z][a-z] means that you're doing it twice. Thus trying to match 2 sequential characters both in the range of a-z.

Here's a live example of the modified version

I highly recommend using regex101.com (which the example above uses), if you're trying to learn regex. As it gives a nice explanation of the regex you entered.

Upvotes: 2

Related Questions