I need to write an AppleScript that can change my files names inside folder.Below is my scenario.
Folder1
|
Folder2
|
imageA.png,imageB.png
Now i need to write an AppleScript that can change name of imageA.png to A.png and imageB.png to B.png.
What should be my AppleScript for this? this is not my exact scenario but i am giving an example above so i can implement more from that.
I have tried below script and it is working well but i am getting error when filename is not exist, means it is not ignoring it.
tell application "Finder"
set the name of file "iOs_142:About1.png" to "About1.png"
set the name of file "iOs_142:FAQs.png" to "FAQs1.png"
end tell
If you really insist on doing this with AppleScript, this should give a template to work forward with:
(* Taken from http://applescript.bratis-lover.net/library/string/#replaceString *)
on replaceString(theText, oldString, newString)
local ASTID, theText, oldString, newString, lst
set ASTID to AppleScript's text item delimiters
try
considering case
set AppleScript's text item delimiters to oldString
set lst to every text item of theText
set AppleScript's text item delimiters to newString
set theText to lst as string
end considering
set AppleScript's text item delimiters to ASTID
return theText
on error eMsg number eNum
set AppleScript's text item delimiters to ASTID
error "Can't replaceString: " & eMsg number eNum
end try
end replaceString
tell application "Finder"
set fs to files of folder POSIX file "/your/folder" as list
end tell
repeat with f in fs
set n to replaceString(name of f, "to be replaced", "")
tell application "System Events" to set name of f to n
end repeat
Related
In the image below, I am trying to edit every file name in the cat directory so it only contains one "." For example, I need the first file name to be cat1.jpg and so forth for all of the other file names.
Do any of you all mind providing me some guidance on how I can implement an AppleScript (with Automator?) to rename all of the files in this cat directory?
Let's assume that all the files you want to rename are in a folder on your desktop named "Cat"
This following AppleScript code will remove the first instance of "." ... Leaving an empty space in its place. So, "cat.1.jpg" will be renamed to "cat 1.jpg" etc.
property theFolder : ((path to desktop) as text) & "Cat"
property originalFileName : missing value
property originalFileNameExtension : missing value
tell application "Finder" to set theFiles to (files of folder theFolder) as alias list
repeat with i from 1 to count of theFiles
set thisItem to item i of theFiles
tell application "System Events"
set fileInfo to thisItem's properties
set {originalFileName, originalFileNameExtension} to ¬
{name of fileInfo, name extension of fileInfo}
end tell
set theOffset to offset of originalFileNameExtension in originalFileName
set shortName to text 1 thru (theOffset - 2) of originalFileName
set text item delimiters to "."
set tempText to every text item of shortName
set text item delimiters to " "
set cleanedName to (tempText as text) & "." & originalFileNameExtension
tell application "System Events" to set name of thisItem to cleanedName
end repeat
This would be a full AppleScript solution to your question. But if this is only a one time event for you, mass renaming of the files through Finder, would be a quicker solution.
Answering the question in the title, once you cycle through strings in a repeat loop, to remove the first instance of a string from a string you can:
Use offset:
set s to "foo.bar.txt"
set o to offset of "." in s
set r to (text 1 thru (o - 1) of s) & (text (o + 1) thru -1 of s)
Use Applescript's Text Item Delimiters:
set AppleScript's text item delimiters to "."
set l to text items of s
set r to (item 1 of l) & (text items 2 thru -1 of l as string)
set AppleScript's text item delimiters to ""
I have been at this for two days.
So, using Automator and Applescript, I need to scan a volume (or volumes) and get a path to each file, the file name plus extension, assetID (if there is one) and output each part to a comma separated csv file.
So far, I have the Automator actions sorted out and most of the Applescript part but I am at my wits end. The paths and file names work but extracting the assetID (if there is one) is the problem. Not every file has an assetID (and those I am not interested in). The assetID is always a 10 digit number at the end of the file preceded by an underscore("_") like so - afilename_1234567890.ext. As it is now, the script will display the assetID's of the files it processes but as soon as it gets to a file with no id, I see the following error, "The action “Run AppleScript” encountered an error: Can’t get text 1 thru -1 of "".” Something is getting munged somewhere.
Any help would be greatly appreciated.
The script so far...
on run {input, parameters}
-- save delimiters to restore old settings
set savedDelimiters to AppleScript's text item delimiters
-- set delimiters to delimiter to be used
set AppleScript's text item delimiters to "/"
repeat with aPath in input
-- set a variable to contain the "/" (POSIX) version of the files path
set filesPath to POSIX path of aPath
-- get the file name
set fileName to last text item of filesPath
-- get the file name without the extension
set thePrefix to text 1 thru ((offset of "." in fileName) - 1) of fileName
-- get the asset ID, if there is one
set assetID to rightStringFromRight(thePrefix, "_")
display dialog assetID
if (class of assetID) is integer then
-- get the path only
set pathOnly to ((text items 1 thru -2 of (get POSIX path of aPath)) as Unicode text) & "/"
-- output the path only, file name and asset ID to a comma delimited csv file
display dialog assetID
end if
end repeat
-- restore the old delimiter setting
set AppleScript's text item delimiters to savedDelimiters
end run
on rightStringFromRight(str, del)
local str, del, oldTIDs
set oldTIDs to AppleScript's text item delimiters
try
set str to str as string
if str does not contain del then return str
set AppleScript's text item delimiters to del
set str to str's last text item
set AppleScript's text item delimiters to oldTIDs
return str
on error eMsg number eNum
set AppleScript's text item delimiters to oldTIDs
error "Can't rightStringFromRight: " & eMsg number eNum
end try
end rightStringFromRight
on is_number(number_string)
try
set number_string to number_string as number
return true
on error
return false
end try
end is_number
I finally got the script working. A few wrong assumptions corrected and all is well.
What i want is to do a find and replace command with applescript. I know I can use namechanger and other programs but that takes too many steps. I'm all about efficiency.
tell application "Finder"
set selected_items to selection
set jobNum to text returned of (display dialog "Job Number:" default answer "")
set name of document folder selection to jobNum (*if it did work it would rename the entire folder which isn't what I want. My goal is to replace all "12345" with the value of jobNum*)
end tell
sample folder structure (i can't submit images yet because I need 10pts)
main folder: 12345_Sample Job Folder
- 12345_D.ai
- 12345_P.ai
- Proofs
- Working Files
- 12345.ai
Try this script:
set jobFolder to choose folder with prompt "Choose the Job Folder:"
tell application "Finder"
set rootName to jobFolder's name
set searchString to my FindSearchString(rootName)
set replaceString to text returned of (display dialog ("This script will search for files that contain " & searchString & ". Please enter the replacement text and click OK.") default answer searchString)
set everything to every file in (jobFolder's entire contents)
repeat with onething in everything
if ((onething's name) as text) contains searchString then
set onething's name to my replace_chars(((onething's name) as text), searchString, replaceString)
end if
end repeat
set jobFolder's name to my replace_chars(((jobFolder's name) as text), searchString, replaceString)
end tell
---------------------------------
on replace_chars(this_text, search_string, replacement_string)
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to the search_string
set the item_list to every text item of this_text
set AppleScript's text item delimiters to the replacement_string
set this_text to the item_list as string
set AppleScript's text item delimiters to astid
return this_text
end replace_chars
---------------------------------
to FindSearchString(txt)
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to "_"
set sst to txt's text item 1
set AppleScript's text item delimiters to astid
return sst
end FindSearchString
This will only affect filenames within the initial chosen folder, not subfolder names. At the very end, it changes the name of the chosen folder.
The renaming handler is based on the code at the bottom of this page
I am working on a Automator workflow, I am passing list of URLs to the "Run Applescript" and I need to fetch the contents of on each page, concatenate and pass it to a BBedit (or any other text editor).
on run {input, parameters}
tell application "BBEdit"
activate
set astid to AppleScript's text item delimiters
set startHere to "<tbody>"
set stopHere to "</tbody>"
repeat with anItem in input
set blurb0 to (do shell script "curl " & anItem)
set AppleScript's text item delimiters to startHere
set blurb1 to text item 2 of blurb0
set AppleScript's text item delimiters to stopHere
set blurb2 to text item 1 of blurb1
set AppleScript's text item delimiters to astid
return blurb2
beep
end repeat
end tell
end run
The current code only properly gets only the contents from first URL. Can anybody fix this?
This subroutine may be what you need (if you're using Safari)...
on getSource(this_URL)
tell application "Safari"
activate
set the URL of the current tab of document 1 to this_URL
set the |source| to the source of the front document
end tell
tell application "TextEdit"
activate
set the text of the front document to the source
end tell
quit application "Safari"
end getSource
Call it using:
repeat with anItem in input
getSource(input)
end repeat
I hope this helps!
Because you are inside the repeat with anItem in input loop it does all your work for the first item and the return exits the loop and in fact the whole Automator action. I think you have never heard the beep from your script ;-)
On the other side I'm wondering why you want BBEdit to do the cUrl and sort work for you. All called handlers don't belong to BBEdit...
I think your handler should look like this:
on run {input, parameters}
-- define a few parameters
set astid to AppleScript's text item delimiters
set startHere to "<tbody>"
set stopHere to "</tbody>"
-- define a list to store all found content
set allFoundContent to {}
repeat with anItem in input
set blurb0 to (do shell script "curl " & anItem)
set AppleScript's text item delimiters to startHere
set blurb1 to text item 2 of blurb0
set AppleScript's text item delimiters to stopHere
-- put the found content at the end of the list
set end of allFoundContent to text item 1 of blurb1
set AppleScript's text item delimiters to astid
end repeat
-- from here you have three possibilities:
-- 1. return the list to next Automator action (uncomment the next line):
-- return allFoundContent
-- 2. concatenate the list with a delimiter you like (here return & "------" & return)
-- and give it to your preferred text editor from this point (uncomment the next lines):
-- set AppleScript's text item delimiters to return & "------" & return
-- tell application "TextEdit"
-- make new document with properties {text: allFoundContent as text}
-- end tell
-- set AppleScript's text item delimiters to astid
-- 3. concatenate the list with a delimiter you like (here return & "------" & return)
-- and give it to the next workflow step, maybe a BBEdit action waiting for a string? (uncomment the next lines):
-- set AppleScript's text item delimiters to return & "------" & return
-- set returnString to allFoundContent as text
-- set AppleScript's text item delimiters to astid
-- return returnString
-- Next decision (for choice 1 or 2):
-- What do you want to give to next Automator action?
-- you can pass your input (the given URLs) (uncomment next line):
-- return input
-- or your result list (uncomment next line):
-- return allFoundContent
end run
Greetings, Michael / Hamburg
I can get the names of all files in a folder by doing this:
tell application "Finder"
set myFiles to name of every file of somePath
end tell
How can I change the strings in myFiles so that they do not include the file extension?
I could for example get {"foo.mov", "bar.mov"}, but would like to have {"foo", "bar"}.
Current solution
Based on the accepted answer I came up with the code below. Let me know if it can be made cleaner or more efficient somehow.
-- 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)
From 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
Single line way of doing it, no Finder, no System Events. So more efficient and faster. Side effect (could be good, or bad): a file name ending with "." will have this character stripped out. Using "reverse of every character" makes it works if the name as more than one period.
set aName to text 1 thru ((aName's length) - (offset of "." in ¬
(the reverse of every character of aName) as text)) of aName
The solution as a handler to process a list of names:
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
Here's an applescriptish method to get Finder's idea of what the stripped filename is but please note it will only work if you have NOT enabled the option in Finder's preferences to "Show all filename extensions":
set extension hidden of thisFile to true
set thisName to displayed name of thisFile
-- display dialog "hey"
set extension hidden of thisFile to false
Here's a full script that does what you wanted. I was reluctant to post it originally because I figured there was some simple one-liner which someone would offer as a solution. Hopefully this solution is not a Rube Goldberg way of doing things.
The Finder dictionary does have a name extension property so you can do something like:
tell application "Finder"
set myFiles to name extension of file 1 of (path to desktop)
end tell
So the above will get you just the extension of the first file on the user's desktop. It seems like there would be a simple function for getting the (base name - extension) but I didn't find one.
Here's the script for getting just the filenames without extension for every file in an entire directory:
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
Though the above script does work if anyone knows a simpler way of doing what the OP wanted please post it cause I still get the sense that there should be a simpler way of doing it. Maybe there's a scripting addition which facilitates this as well. Anyone know?
Based on Lauri Ranta's nice solution, which works for extensions that Finder doesn't know about:
set delims to AppleScript's text item delimiters
set AppleScript's text item delimiters to "."
set myNames to {}
tell application "Finder"
set myFiles to name of every file of (path to Desktop)
repeat with myfile in myFiles
set myname to name of file myfile
if myname contains "." then set myname to (text items 1 thru -2 of myname) as text
set end of myNames to myname
end repeat
end tell
set AppleScript's text item delimiters to delims
return myNames
I don't know how to remove the extensions when you use the "every file"
syntax but if you don't mind looping (loop not shown in example) through each file then this will work:
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
Within a tell "Finder" block this collects file names stripped of the extension in 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
For a single file I found the answer here, copied below.
set theFileName to "test.jpg"
set thePrefix to text 1 thru ((offset of "." in theFileName) - 1) of theFileName
This is a little more than you need, but it will handle more than one "." in a file name.
Assuming that a file alias is passed in to the method.
on Process(myFileAlias)
set myFile to myFileAlias as string
set AppleScript's text item delimiters to ":"
set myItemCount to the number of text items in myFile
set myFileName to the last text item of myFile
set myFilePath to text items 1 through (myItemCount - 1) of myFile
set AppleScript's text item delimiters to "."
set myItemCount to the number of text items in myFileName
set myExtension to the last text item of myFile
// This line is the key.
set myShortFilename to text items 1 through (myItemCount - 1) of myFileName as string
log (myFileName)
log (myShortFilename)
end