有没有办法使用模式删除给定目录中的所有文件(不递归)?
举个例子,我有一个名为一些文件file1.jpg,file2.jpg,file3.jpg等,我想知道如果有一个acceps这样的UNIX命令通配符的任何方法:
rm file*.jpg
Run Code Online (Sandbox Code Playgroud)
use*_*681 17
试试这个:
- (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];
}
}
}
Run Code Online (Sandbox Code Playgroud)
为你的例子
file1.jpg,file2.jpg,file3.jpg
你可以使用如下:
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^file.*\.jpg$"
options:NSRegularExpressionCaseInsensitive
error:nil];
[self removeFiles:regex inPath:NSHomeDirectory()];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2461 次 |
| 最近记录: |