Переименование файлов на основе электронной таблицы чисел с помощью Applescript / Automator - PullRequest
0 голосов
/ 28 ноября 2018

У меня есть appleScript для переименования файлов на основе имен, представленных в электронной таблице чисел.

Каждое изображение имеет три разных размера, каждый размер в одной папке.Таким образом, существует

/ 50 / exportedImage-01.svg

/ 33 / exportedImage-01.svg

/ 25 / exportedImage-01.svg

Сценарий работает совершенно нормально и делает то, что должен, но он мучительно медленный и останавливается на 50+ файлах.Поскольку у меня есть несколько сотен файлов для переименования, возникает вопрос:

Есть ли способ изменить сценарий, чтобы сделать его более эффективным / мощным?

Рабочий процесс выглядит следующим образом:

  • чтение файла чисел - новые имена (featuredImage) в столбце B, старые имена (exportedImage) в столбце C
  • перебирают файлы в первой папке и переименовывают их в соответствии со столбцом B
  • цикл по файлам во второй папке и переименование их в соответствии со столбцом B
  • цикл по файлам в третьей папке и переименование их согласно столбцу B

Вот что я получил такfar:

set numbersFile to choose file with prompt "Choose the Numbers file" of type {"numbers", "XLS7", "XLS8", "XLSX"}
set theFolder to choose folder with prompt "Choose the folder 50 containing the files to rename"
--get a list of the old and the new filenames
set exportedImage to {}
set featuredImage to {}
tell application "Numbers"
    open numbersFile
    tell table 1 of sheet 1 of document 1
    --tell document 1
    --tell sheet 1
    repeat with i from 1 to row count
        if value of cell ("C" & i as text) > "" then
            set exportedImage to exportedImage & value of cell ("C" & i as text)
            set featuredImage to featuredImage & value of cell ("B" & i as text)
        else
            exit repeat
        end if
    end repeat
    --end tell
end tell
close window 1
end tell

--loop through the files in folder 50 and rename them
tell application "Finder"
    repeat with k from 1 to (count of (get every item of theFolder))
        repeat with i from 1 to count of exportedImage
            if (name of item k of theFolder) as text = (item i of exportedImage) as text then
                set name of (item k of theFolder) to (item i of featuredImage as text)
            end if
        end repeat
    end repeat
end tell

--loop through the files and rename them 33
set theFolder to choose folder with prompt "Choose the folder 33 containing the files to rename"
tell application "Finder"
    repeat with k from 1 to (count of (get every item of theFolder))
        repeat with i from 1 to count of exportedImage
            if (name of item k of theFolder) as text = (item i of exportedImage) as text then
                set name of (item k of theFolder) to (item i of featuredImage as text)
            end if
        end repeat
    end repeat
end tell

--loop through the files and rename them 25
set theFolder to choose folder with prompt "Choose the folder 25 containing the     files to rename"
tell application "Finder"
    repeat with k from 1 to (count of (get every item of theFolder))
        repeat with i from 1 to count of exportedImage
            if (name of item k of theFolder) as text = (item i of exportedImage) as text then
                set name of (item k of theFolder) to (item i of featuredImage as text)
            end if
        end repeat
    end repeat
end tell

Я бы хотел придерживаться яблочного сценария, потому что этот скрипт является частью большего рабочего процесса автоматизатора.

Любая помощь приветствуется, спасибо!

1 Ответ

0 голосов
/ 29 ноября 2018

Я потратил некоторое время, чтобы закончить свой первый комментарий.Позвольте мне объяснить, как вы можете использовать команду 'find'.

Мы ищем имя файла "ExportedImage1.svg" в папке "/ Users / Document / Folder50 /".Команда оболочки: find /Users/Document/Folder50/ExportedImage1.svg

Команда «Найти» может быть улучшена с помощью функции «-exec».Для каждого найденного файла -exec будет применять команду сразу после.В exec следующая команда может использовать {}, что означает файл, найденный в команде find.наконец, но не в последнюю очередь, синтаксис требует ';'в конце.

Пример: find path / file.svg -exec mv {} path / newName.svg ';'

Поиск пути / file.svg и, если он найден,он применяет команду mv (переместить или переименовать) к этому файлу {} с новым значением path / newName.svg.

В приведенном ниже сценарии я использовал Excel (потому что у меня нет номеров!), но выможете легко настроить первый блок скрипта, чтобы использовать ваши номера.

Также я изменил вашу логику, выполнив цикл по всей строке данных Excel (второе двоеточие = экспортированное изображение).Внутри этого цикла для каждой строки изображения / Excel я перебираю 3 выбранные вами папки (25, 33 и 50).внутри этого цикла я ищу файл в папке и, если он найден, я изменяю имя, используя первый двоеточие файла Excel (FeaturedImage).

Я предполагаю, что расширения файлов всегда '.svg'

-- you must replaced that block by your Numbers block
set numbersFile to choose file with prompt "Choose the Numbers file" of type {"numbers", "XLS7", "XLS8", "XLSX"}
tell application "Microsoft Excel"
-- my Excel file is made of column B=FeaturedImage (will be new file names) and column C=ExportedImage (current file name)
-- I assume that name in files have no extension '.svg'
    open numbersFile
    tell active sheet to set myData to value of used range
    close window 1
    -- myData is list of rows: each item is a list made of 2 values : value in col B and value in col C
end tell


-- select the 3 folders
set folder50 to choose folder with prompt "Choose the folder 50 containing the files to rename"
set folder33 to choose folder with prompt "Choose the folder 33 containing the files to rename"
set folder25 to choose folder with prompt "Choose the folder 25 containing the files to rename"
-- build a list of the 3 folders
set myFolders to {POSIX path of folder50}
set myFolders to myFolders & {POSIX path of folder33}
set myFolders to myFolders & {POSIX path of folder25}


repeat with myRow in myData -- loop through all data rows   
    repeat with aFolder in myFolders -- loop through folders : 25, 33, 50

        -- search file name = item 2 of myRow (=ExportedImage) in folder 50 and if find, rename to item 1 of myRow
        set curPath to quoted form of (aFolder & (item 2 of myRow) & ".svg") -- the complete path/name to search
        set newPath to quoted form of (aFolder & (item 1 of myRow) & ".svg") -- the complete path/name to replace/rename
        try -- to avoid error in case file not found in the folder
            do shell script "find " & curPath & " -exec mv {} " & newPath & " ';'"
        end try
    end repeat -- next folder 25, 33, 50
end repeat -- next data row

Оптимизация циклов и использование 'find - exec' делают этот скрипт намного быстрее, чем ваш !!

...