Duck
Duck

Reputation: 35953

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

Upvotes: 4

Views: 3418

Answers (2)

Rip Ryness
Rip Ryness

Reputation: 651

Swift version

func removeFiles(regEx:NSRegularExpression, path:String) {
    let filesEnumerator = NSFileManager.defaultManager().enumeratorAtPath(path)
    while var file:String = filesEnumerator?.nextObject() as? String {
        let match = regEx.numberOfMatchesInString(file, options: nil, range: NSMakeRange(0, file.length))
        if match > 0 {
            NSFileManager.defaultManager().removeItemAtPath(path.stringByAppendingPathComponent(file), error: nil)
        }
    }
}

Upvotes: 0

user478681
user478681

Reputation: 8329

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()];

Upvotes: 17

Related Questions