In my directory I've following filename pattern:
1. Pattern
2018_09_01_Filename.java
or
2. Pattern
kit-deploy-190718_Filename.java
Now I'm trying to select every file in the directory which is matching with the first pattern (the date can be different but it's always year_month_day). But I don't get any further.
I've been thinking that I could split the basename from the file so that I get the first ten characters. Then I'll look if this is matching with a pattern.
my $filename = basename($file);
my $chars = substr($filename, 0 , 10);
if ($chars =~ m/2000_01_01/) {
print "match\n";
}
else {
print "Don't match";
}
You just need a regex that matches your needs, example:
#!/usr/bin/perl
my $filename = "2018_09_01_Filename.java";
if ($filename =~ m/\D?20\d{2}_\d{2}_\d{2}\D?/) {
print "match\n";
}
Explanation
\D?
matches any character that's not a digit
?
Quantifier — Matches between zero and one times, as many times as possible, giving back as needed (greedy)20
matches the characters 20 literally (case sensitive)
\d{2}
matches a digit
{2}
Quantifier — Matches exactly 2 times_
matches the character _
literally
\d{2}
matches a digit
{2}
Quantifier — Matches exactly 2 times_
matches the character _
literally
\d{2}
matches a digit
{2}
Quantifier — Matches exactly 2 times\D?
matches any character that's not a digit
?
Quantifier — Matches between zero and one times, as many times as possible, giving back as needed (greedy)Check the demo