Добавление или замена текущей даты в конце имени файла или папки - PullRequest
0 голосов
/ 02 апреля 2019

Хотелось бы немного помочь с appleScript, который переименует текущий выбранный файл или папку, добавив текущую дату (ГГГГ-ММ-ДД) в конце имени файла перед расширением файла, или если в файле существует дата затем обновите его до текущей даты.

Например:

Изображение 1.jpeg

до

Изображение 1 2019-04-02.jpeg

Я уже нашел несколько полезных фрагментов кода из Новая папка Applescript, названная по дате и https://gist.github.com/mnot/221399

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

Не уверен, что это будет иметь какое-либо значение, но было бы безопасно предположить, что ни один файл не будет заканчиваться в XXXX-XX-XX (X = любая цифра).


tell application "Finder"
    try
        set the source_folder to (folder of the front window) as text
    on error -- no open folder windows
        display dialog "Please select a file to apply date to" buttons {"Cancel"} default button 1
    end try
    set these_items to the selection
end tell

repeat with i from 1 to the count of these_items
    set this_item to (item i of these_items) as alias
    set this_info to info for this_item
    set {file_name, file_ext} to splitExtension from the name of this_info
    set x to my the_perfect_datestring()
    set new_name to file_name & " " & x & "" & file_ext
    -- check to see if it's already there
    tell application "Finder"
        try
            set name of this_item to new_name
        on error -- no open folder windows
            display dialog "Error - File may already exist" buttons {"Cancel"} default button 1
        end try
    end tell
end repeat


on the_perfect_datestring()
    try
        set cd to (the current date)
        set the_year to year of (cd) as number
        set the_month to month of (cd) as number
        set the_day to day of (cd) as number
        if the_month < 10 then set the_month to "0" & the_month
        if the_day < 10 then set the_day to "0" & the_day
        return ((the_year & "-" & the_month & "-" & the_day) as text)
    on error
        return "-ERROR"
    end try
end the_perfect_datestring


to splitExtension from file_name
    set dot to "."
    tell AppleScript
        set oT to text item delimiters
        set text item delimiters to dot
        if (count text items of file_name) > 1 then
            set out_name to (text items 1 through -2 of file_name) as string
            set ext to last text item of file_name
        else
            set out_name to file_name
            set ext to ""
        end if
        set text item delimiters to oT
        if ext is not "" then set ext to dot & ext
        return {out_name, ext}
    end tell
end splitExtension

Заранее спасибо

1 Ответ

0 голосов
/ 02 апреля 2019

Это еще один подход, который создает метку времени с оболочкой и проверяет, существует ли дата с NSRegularExpression Foundation рамки

use AppleScript version "2.4" -- Yosemite (10.10) or later
use framework "Foundation"
use scripting additions

-- the pattern searches for 4 digits, one hyphen, 2 digits, one hyphen, 2 digits at the end of the string
property datePattern : "\\d{4}-\\d{2}-\\d{2}$"

tell application "Finder"
    try
        set the sourceFolder to (folder of the front window) as text
    on error -- no open folder windows
        display dialog "Please select a file to apply date to" buttons {"Cancel"} default button 1
    end try
    set theseItems to the selection
end tell

repeat with anItem in theseItems
    -- extract file name and file extension
    set {name:Nm, name extension:fileExtension} to anItem
    -- strip the file extension
    set baseName to text 1 thru ((get offset of "." & fileExtension in Nm) - 1) of Nm
    -- create the timestamp in format YYYY-MM-DD
    set currentDate to do shell script "/bin/date +%Y-%m-%d"
    if fileNameHasDate(baseName) then
        -- replace the last 11 characters with the new timestamp
        set newName to text 1 thru -11 of baseName & currentDate
    else
        -- append the timestamp to the file name
        set newName to baseName & space & currentDate
    end if
    -- add the file extension if there was one
    if fileExtension is not "" then set newName to newName & "." & fileExtension
    -- rename the file
    tell application "Finder" to set name of contents of anItem to newName
end repeat

-- checks if the date string exists in the filename. Returns boolean true or false
on fileNameHasDate(fileName)
    set regex to current application's NSRegularExpression's regularExpressionWithPattern:datePattern options:0 |error|:(missing value)
    set numberOfMatches to regex's numberOfMatchesInString:fileName options:0 range:{location:0, |length|:(count fileName)}
    return (numberOfMatches as integer) is 1
end fileNameHasDate

Примечание: поскольку AppleScriptObjC участвует lowerCamelCased используются имена переменных

...