HezelTm
HezelTm

Reputation: 25

Regex to search all directories whose name contains one of the two substrings

I'm a actually working on a Bash Script that search the backups directories to delete.

I have a directory ~/test/ that contain some "backups" directories named as follow :

20200302_000001-daily
20200330_000001-monthly
20200528_000001-weekly
20200529_000001-daily
20200530_000001-daily
20200531_000001-monthly
20200601_000001-daily
20200602_000001-daily

With a find command, I'm trying to record all directory's name that contain the string daily or weekly in an array :

BACKUPS=(`find $BACKUP_DIR -maxdepth 1 -regex ".*[daily|weekly]$"`) // where $BACKUP_DIR is the absolute path to the "test" directory.

The problem is, that the regex match all the backups directories and after hours of research, I didn't find why.

It's interesting to know that if I use the regex .*daily$, the regex match all the "daily" backups directories (and .*weekly$ match all the "weekly" backups directories).

I know there are other ways to do it, but I really want to success with a regex.

Upvotes: 2

Views: 1353

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626845

You may use a regex that will match the whole input and contains a grouping construct rather than a bracket expression:

BACKUPS=(`find $BACKUP_DIR -maxdepth 1 -regex ".*/.*\(daily\|weekly\)$"`)

Here, the POSIX BRE pattern means:

  • .*/ - match any 0 or more chars up to the last /
  • .* - any 0 or more chars up to
  • \(daily\|weekly\) - either daily or weekly character sequences (note that [day|week] is the same as [adekwy|] since it is a bracket expression)
  • $ - end of string.

Upvotes: 1

Related Questions