What is character class in bash shell linux and how to use them to search a pattern ?

In Linux, Character Classes is a group of characters which are responsible to perform pattern matching.

Character Classes are defined using “[]” i.e. square brackets and matches any of the mentioned patterns.

 

I. Few examples of Character Class

Any character                              -->  "." dot special character.
All lower case alphabets                   -->  [a-z]
Upper case alphabets                       -->  [A-Z]
Match lower and upper case character "e"   -->  [eE]
And so on......

 

II. How to use character class ?

### Create a text file below.
ngelinux saket$ cat testfile 
Welcome to NGELinux.
This is a sample file.
Here we will see chracter class example.
It works on ArchLinux, and other Linux versions also.
ngelinux saket$ 

### Example 1: Match any of the "eEhHL"Linux pattern.
$ awk '/[eEhHL]inux/{print $0}' testfile 
Welcome to NGELinux.
It works on ArchLinux, and other Linux versions also.
ngelinux saket$ 

### Example 2: Look for lower case w character.
$ awk '/[w]/{print $0}' testfile 
Here we will see chracter class example.
It works on ArchLinux, and other Linux versions also.

### Example 3: Look for either lowercase or uppercase character w.
$ awk '/[wW]/{print $0}' testfile 
Welcome to NGELinux.
Here we will see chracter class example.
It works on ArchLinux, and other Linux versions also.

In a similar fashion above, we can make any set of character class and do the pattern matching as per our convenience.

Leave a Reply

avatar
  Subscribe  
Notify of