Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove files matching a pattern in iOS

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
like image 907
Duck Avatar asked Dec 04 '22 08:12

Duck


1 Answers

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()];
like image 125
user478681 Avatar answered Dec 15 '22 18:12

user478681