如何以编程方式更改文件名

时间:2012-06-21 20:08:40

标签: macos

任何人都可以告诉我如何将文件名附加到字符串“@ 2x”的特定文件夹中。我宁愿不去手动重命名每个文件的麻烦。感谢。

3 个答案:

答案 0 :(得分:3)

启动AppleScript编辑器并粘贴以下脚本:

set appendable to "@2x"
set theFolder to choose folder
tell application "Finder"
    set theFiles to (files of entire contents of theFolder) as alias list
    repeat with theFile in theFiles
        set FileExtension to theFile's name extension as string
        set FileName to theFile's name as string
        set FileBaseName to text 1 thru ((offset of "." in FileName) - 1) of FileName
        set theFile's name to FileBaseName & appendable & "." & FileExtension
    end repeat
end tell

脚本将“@ 2x”附加到所选文件夹中的所有文件 只需点击“运行”按钮并选择任何文件夹即可执行脚本。

答案 1 :(得分:1)

从终端你可以运行 for f in *; do mv f 'f@2X'; done;

答案 2 :(得分:1)

您可以使用 Automator 执行此操作,无需任何代码。

或者,正如您已经知道“ Xcode ”和 Objective-C ,这是一个在名称扩展名之前添加@2X的示例。

BOOL result;
NSString *fullPath, *filename, *newName;
NSString *dir = @"/Users/jack/Desktop/Untitled 1";
NSFileManager *fm = [NSFileManager defaultManager];
NSEnumerator *enumerator = [[fm contentsOfDirectoryAtPath:dir error:nil] objectEnumerator];

while(filename=[enumerator nextObject]){
    if ([filename hasPrefix:@"."]) { continue;}//skip files that begin with a dot
    fullPath = [dir stringByAppendingPathComponent:filename];
    if (!([fm fileExistsAtPath:fullPath isDirectory:&result]&&result)) { // skip directory
        if ([[filename pathExtension] isEqualToString:@""]) {
            newName = [fullPath stringByAppendingString:@"@2X"];// no extension
        } else {
            newName = [[fullPath stringByDeletingPathExtension] stringByAppendingFormat:@"@2X.%@",[filename pathExtension]];
        }
        result = [fm moveItemAtPath:fullPath toPath:newName error:nil];
    }
}