Applescript: получить имена файлов в папке без расширения - PullRequest
7 голосов
/ 25 ноября 2010

Я могу получить имена всех файлов в папке, выполнив следующее:

tell application "Finder"
    set myFiles to name of every file of somePath
end tell

Как я могу изменить строки в myFiles, чтобы они не включали расширение файла?

Я мог бы, например, получить {"foo.mov", "bar.mov"}, но хотел бы иметь {"foo", "bar"}.


Текущее решение

На основании принятого ответа я пришел с кодом ниже,Дайте мне знать, если это можно сделать чище или эффективнее.

-- Gets a list of filenames from the
on filenames from _folder

    -- Get filenames and extensions
    tell application "Finder"
        set _filenames to name of every file of _folder
        set _extensions to name extension of every file of _folder
    end tell

    -- Collect names (filename - dot and extension)
    set _names to {}
    repeat with n from 1 to count of _filenames

        set _filename to item n of _filenames
        set _extension to item n of _extensions

        if _extension is not "" then
            set _length to (count of _filename) - (count of _extension) - 1
            set end of _names to text 1 thru _length of _filename
        else
            set end of _names to _filename
        end if

    end repeat

    -- Done
    return _names
end filenames

-- Example usage
return filenames from (path to desktop)

Ответы [ 7 ]

6 голосов
/ 21 сентября 2012

С http://www.macosxautomation.com/applescript/sbrt/index.html:

on remove_extension(this_name)
  if this_name contains "." then
    set this_name to ¬
    (the reverse of every character of this_name) as string
    set x to the offset of "." in this_name
    set this_name to (text (x + 1) thru -1 of this_name)
    set this_name to (the reverse of every character of this_name) as string
  end if
  return this_name
end remove_extension
4 голосов
/ 20 декабря 2016

Однострочный способ сделать это, без Finder, без системных событий. Так эффективнее и быстрее. Побочный эффект (может быть хорошим или плохим): имя файла заканчивается на «.» будет убран этот персонаж. Использование «реверса каждого символа» делает его работоспособным, если имя больше одного периода.

set aName to text 1 thru ((aName's length) - (offset of "." in ¬
    (the reverse of every character of aName) as text)) of aName

Решение как обработчик для обработки списка имен:

on RemoveNameExt(aList)
    set CleanedList to {}
    repeat with aName in aList
        set the end of CleanedList to text 1 thru ((aName's length) - (offset of ¬
            "." in (the reverse of every character of aName) as text)) of aName
    end repeat
    return CleanedList
end RemoveNameExt
4 голосов
/ 17 октября 2013

Вот яблочный метод, чтобы получить представление Finder о том, что такое раздетое имя файла:

set extension hidden of thisFile to true
set thisName to displayed name of thisFile
-- display dialog "hey"
set extension hidden of thisFile to false
3 голосов
/ 26 ноября 2010

Вот полный скрипт, который делает то, что вы хотели.Я не хотел публиковать его первоначально, потому что я полагал, что есть какая-то простая однострочная строка, которую кто-то предложит в качестве решения.Надеемся, что это решение не является Rube Goldberg способом ведения дел.

Словарь Finder имеет свойство extension name , так что вы можете сделать что-то вроде:

tell application "Finder"
   set myFiles to name extension of file 1 of (path to desktop)
end tell

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

Вот скрипт для получения только имен файлов без расширения для каждого файла во всем каталоге:

set filesFound to {}
set filesFound2 to {}
set nextItem to 1

tell application "Finder"
  set myFiles to name of every file of (path to desktop) --change path to whatever path you want   
end tell

--loop used for populating list filesFound with all filenames found (name + extension)
repeat with i in myFiles
  set end of filesFound to (item nextItem of myFiles)
  set nextItem to (nextItem + 1)
end repeat

set nextItem to 1 --reset counter to 1

--loop used for pulling each filename from list filesFound and then strip the extension   
--from filename and populate a new list called filesFound2
repeat with i in filesFound
  set myFile2 to item nextItem of filesFound
  set myFile3 to text 1 thru ((offset of "." in myFile2) - 1) of myFile2
  set end of filesFound2 to myFile3
  set nextItem to (nextItem + 1)
end repeat

return filesFound2

Хотя приведенный выше скрипт действительно работает, если кто-то знает более простой способ сделать то, что хотел OP, пожалуйста, опубликуйте его, потому что я все еще чувствую, что должен быть более простой способ сделать это.Может быть, есть дополнение для сценариев, которое также облегчает это.Кто-нибудь знает?

2 голосов
/ 16 октября 2012

На основе хорошего решения Лаури Ранты , которое работает для расширений, о которых Finder не знает:

2 голосов
/ 25 ноября 2010

Я не знаю, как удалить расширения, когда вы используете «каждый файл» синтаксис, но если вы не возражаете зацикливание (цикл не показан в примере) для каждого файла, то это будет работать:

tell application "Finder"
  set myFile to name of file 1 of somePath
  set myFile2 to text 1 thru ((offset of "." in myFile) - 1) of myFile
end tell
1 голос
/ 29 декабря 2015

В блоке Tell "Finder" он собирает имена файлов без расширения в myNames:

repeat with f in myFiles
    set myNames's end to ¬
        (f's name as text)'s text 1 thru -(((f's name extension as text)'s length) + 2)
end repeat
...