Regex pattern for multiple digits

Hello,

I need to construct a pattern to match the below string (especially the timestamp at the beginning)

20101222100436_temp.dat

The below pattern works [0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]_temp.dat

However I am trying find if there are any other better representations.
I tried [\d]{14}, but it did not work.

I am on RedHat Linux 2.6.

Thanks.

It will depend on what program you are using the regex on, grep, sed, perl, awk, etc.

Use just \d , as [\d] will match "d" only.

I am trying this on a ls program.

ls -l \d{14}_temp.dat

The above command does not give the expected result. I'm trying to fish the file 20101222100436_temp.dat.

Most commonly used shells do not support \d for file-globbing. If you are using man bash (linux), the command line you entered would be interpreted as:

ls -l d{14}_temp.dat

You are going to have to stick with, as you put it, the "pattern that works".

1 Like

File globbing is not regex. You have ? not ., * not .*, [abc] in both, but not [^abc] or * or {##} of regex!

You can model date ranges more accurately, e.g., for 1900-2099:

 
  [21][90][0-9][0-9][01][0-9][0-3][0-9][0-2][0-9][0-5][0-9[0-5][0-9]_tmp.dat

You could write your dates into the file name with a little punctuation, for clarity and mistake prevention, like:

 
  2010-12-29_14:56:07_temp.dat

If less accuracy is allowed you could use extended globbing in ksh93/bash

ls -l +([0-9])_temp.dat

( in bash use shopt -s extglob if extended globbing is not in by default )

--
In a recent ksh93 (version l or later) you can even do exact matching like this:

ls -l {14}([0-9])_temp.dat
1 Like