Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding only numbers at the beginning of a filename with regex

Tags:

regex

bash

I'm (a regex noob) trying to find only the files in a directory that begin with numbers and not strings.

My regex is

 .*/^\d+\w+[A][D][0-5][0-9].mat

(The end of the file name has the letters AD and then numbers from 0-54 before the MAT extension. I include ./ because I am going to pass this to find in bash.)

However, this returns false for both files like

./times_121312_going_down_AD33.mat

and

./121312_going_down_AD33.mat

What am I doing wrong?

like image 798
mac389 Avatar asked Dec 05 '22 12:12

mac389


1 Answers

Here's a working example with find

$ ls -l *.mat
-rw-r--r-- 1 root root 0 Jan 13 15:09 121312_going_down_AD33.mat
-rw-r--r-- 1 root root 0 Jan 13 15:09 times_121312_going_down_AD33.mat

$ find . -type f -regex '.*/[0-9]+_.*AD[0-5][0-9]\.mat$'
./121312_going_down_AD33.mat

\d and \w don't work in POSIX regular expressions, you could use [:digit:] tho

The regular expression explained

  • .* repeat any character except\n, zero or more times
  • / match character '/' literally
  • [0-9]+ repeat any char in 0 to 9, one or more times
  • _ match character '_' literally
  • .* repeat any character except\n, zero or more times
  • A match character 'A' literally
  • D match character 'D' literally
  • [0-5] Match any char in 0 to 5
  • [0-9] Match any char in 0 to 9
  • \. match '.' literally
  • m match 'm' literally
  • a match 'a' literally
  • t match 't' literally
  • $ end of string

If you just want to match all files beginning with an integer you can break it down to .*/[0-9] which would also match ./12/test.tmp and ./12_not_a_mat_file.txt

like image 179
Michel Feldheim Avatar answered Feb 18 '23 06:02

Michel Feldheim