Is there any way to remove all files in a given directory (not recursively) using a pattern?
As an example, I have some files named file1.jpg
, file2.jpg
, file3.jpg
, etc., and I want to know if there is any method that acceps wildcards like this UNIX command:
rm file*.jpg
Try this:
- (void)removeFiles:(NSRegularExpression*)regex inPath:(NSString*)path {
NSDirectoryEnumerator *filesEnumerator = [[NSFileManager defaultManager] enumeratorAtPath:path];
NSString *file;
NSError *error;
while (file = [filesEnumerator nextObject]) {
NSUInteger match = [regex numberOfMatchesInString:file
options:0
range:NSMakeRange(0, [file length])];
if (match) {
[[NSFileManager defaultManager] removeItemAtPath:[path stringByAppendingPathComponent:file] error:&error];
}
}
}
for your example
file1.jpg, file2.jpg, file3.jpg
you can use as follows:
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^file.*\.jpg$"
options:NSRegularExpressionCaseInsensitive
error:nil];
[self removeFiles:regex inPath:NSHomeDirectory()];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With