How to list file with a regular expression pattern in linux using a command

Posted on

This is just an additional trick to list files in a folder. The file listing is done in the linux operating system. But the listing process is not trying to list all files. All the file listed must be in a certain pattern. In order to be able to list all of those files, there is a specific command to achieve it. As an additional, the file listing has a specific pattern. Before listing files with the specific pattern, below is the normal command for listing all the files :

ls -al

For an example, the following is the command execution :

user@localhost:~/data$ ls -al 
...
-rw-r--r-- 1 backup root  12632843 Sep 30 01:00 dbbackup_30092018.pgdump
-rw-r--r-- 1 backup root  14202229 Oct 30 01:00 dbbackup_30102018.pgdump
-rw-r--r-- 1 backup root  15721375 Nov 30 01:00 dbbackup_30112018.pgdump
-rw-r--r-- 1 backup root  17766626 Dec 30 01:00 dbbackup_30122018.pgdump
-rw-r--r-- 1 backup root  24914484 Jan 31 01:00 dbbackup_31012019.pgdump
-rw-r--r-- 1 backup root  10336927 Aug 31  2018 dbbackup_31082018.pgdump
-rw-r--r-- 1 backup root  14234138 Oct 31 01:00 dbbackup_31102018.pgdump
-rw-r--r-- 1 backup root  14979520 Dec 31 01:00 dbbackup_31122018.pgdump
user@localhost:~/data$

The command for listing the file with a specific regular expression pattern. The main goal is to list all of the file with has the pattern of ‘122018’. It is marking the created file in December 2018. So,the following is the command pattern :

user@localhost:~/data$ ls -al | grep 'dbbackup_[0-9][0-9]122018
...
-rw-r--r-- 1 backup root  17766626 Dec 30 01:00 dbbackup_30122018.pgdump
-rw-r--r-- 1 backup root  14979520 Dec 31 01:00 dbbackup_31122018.pgdump
user@localhost:~/data$

The above pattern is a pattern for listing all the files containing the characters ‘dbbackup_’ followed by two digit and finally with the digit of ‘122018’.

The ‘^’ character is not working in the above pattern to specify and restrict the pattern dbbackup is a beginning pattern. It is because the beginning output of the ‘ls -al’ command is ‘-rw-‘.

Sadly, upon writing this article, the pattern for specifying minimum and maximum occurrence of the pattern of the digit number is still not working.So, the pattern [0-9][0-9] is a certain pattern for defining the maximum digit number representing the digit date. But the pattern itself is still not fully correct. Because a date can contain only one digit.

Leave a Reply