How to store regular expression in a variable?

Hi,

Im facing a weird behavior storing regular expression in a vaiable.

Let us consider

>file_name=CTP02_[0-9]*.tar

when I echo the above variable its displaying below which is file

CTP02_[0-9]*tar

but when I create a file with name CTP02_1234.tar , and when I echo $file_name its showing CTP02_1234.tar not CTP02_[0-9]*tar.gz Why this issue ? How to overcome ? I need to need to use this in grep

My scenario is, to find the number of files which are of type CTP02_[0-9]*.tar in a folder.

Appreciate your help

Thanks

CTP02_[0-9]*.tar is not a regular expression, it is a glob.
And it gets interpreted and expanded before echo shows.

[aia@localhost rdineshredy]$ ls
[aia@localhost rdineshredy]$ touch CTP02_{0..9}.something.tar
[aia@localhost rdineshredy]$ ls
CTP02_0.something.tar  CTP02_3.something.tar  CTP02_6.something.tar  CTP02_9.something.tar
CTP02_1.something.tar  CTP02_4.something.tar  CTP02_7.something.tar
CTP02_2.something.tar  CTP02_5.something.tar  CTP02_8.something.tar
[aia@localhost rdineshredy]$ tar_files="CTP02_[0-9]*.tar"
[aia@localhost rdineshredy]$ echo $tar_files
CTP02_0.something.tar CTP02_1.something.tar CTP02_2.something.tar CTP02_3.something.tar CTP02_4.something.tar CTP02_5.something.tar CTP02_6.something.tar CTP02_7.something.tar CTP02_8.something.tar CTP02_9.something.tar
[aia@localhost rdineshredy]$ rm -f CTP02_*
[aia@localhost rdineshredy]$ ls
[aia@localhost rdineshredy]$ echo $tar_files
CTP02_[0-9]*.tar
[aia@localhost rdineshredy]$ 

And the fix is

echo "$file_name"

Note that you don't grep a folder (usually called a directory in UNIX and Linux environments). The grep utility searches for text in the contents of text files (not directories on most systems).

If you're trying to count the number of files in a directory that have names matching the globbing pattern stored in your shell variable named (confusingly) file_name , you could try something like:

ls $file_name | wc -l

which should work as long as there aren't any newline characters in your file names. If you have users who create filenames containing newline characters, or if you just want to use shell built-ins, a fast way to get what you want is:

set -- $file_name
echo $#

(assuming that you aren't using command line arguments or have already gathered what you need from them, and assuming that at least one file matching your pattern exists) or, if there might not be any matching files (but there also might be a file with a name that is your pattern):

set -- $file_name
if [ "$file_name" = "$1" ] && [ ! -e "$1" ]
then	echo 0
else	echo $#
fi