Piping a list of directories into a regex to do a date compare

I’m learning Elixir with some introductory resources and am trying to understand lists, piping and pattern matching with a real world example.

I have a list of directories with dates in their names such as:

app-backup-2019-04-28-23-00-05 app-backup-2019-05-01-23-00-05
app-backup-2019-04-29-23-00-05 app-backup-2019-05-02-23-00-05
app-backup-2019-04-30-23-00-03

I wish to extract the year and month and compare it against the day of the week for further processing (I’ll be deleting the directories that don’t match Sunday).

I have the following so far:

File.ls!(path) |> Enum.map(&String.split(&1, “-”)) |> List.flatten() |>

But I’m unsure as to where to go from there - should I be feeding the path directly into regex or use Enum.each?

Hello naturastudere and welcome!

Try Enum.filter with Timex:

File.ls!(path) 
|> Enum.filter(fn d -> 
  Timex.parse!(d, "app-backup-{YYYY}-{0M}-{D}-{h24}-{m}-{s}")
  |> Timex.weekday != 7 
end)

results in

["app-backup-2019-04-29-23-00-05", "app-backup-2019-05-02-23-00-05",
 "app-backup-2019-04-30-23-00-03", "app-backup-2019-05-01-23-00-05"]

Elixir has some very good libraries which can do a lot of the heavy lifting for you.
No need to parse the dates for yourself, use the help of Timex.

Enum.filter keeps all elements of a list or map, for which the provided function returns true (in this case the comparison of the weekday with 7).

In case you want to keep the directories that match sundays, you just have to change the comparison to == instead of !=.

3 Likes