I'm trying to write a small gpx file conversion script. The conversion part is done but I can't fix the naming of the converted file. I want the filename of the converted file like this:
originalfilename.2.gpx
This is the code I have so far:
-- begin script
-- For converting from one format to another. Preset to convert from GPX to KML. Tailor as needed. Read the documentation for your version
--Based on the script by Robert Nixon, http://www.gpsbabel.org/os/OSX_oneclick.html
-- This is set up for gpsbabel installed using DarwinPorts. See <http://www.gpsbabel.org/osnotes.html> for details
-- This script is not being actively supported, but you may get some help from the gpsbabel discussion group: <http://www.gpsbabel.org/lists.html>
--start script
-- HINT a '~/' is your home folder and of course the double hyphen is a comment. Remove to make active.
-- setting path for gpsbabel. Reset as needed
--set gpsBabelLocation to "/opt/local/var/db/dports/software/gpsbabel/1.2.7_0/opt/local/bin/" -- DarwinPorts Default for Tiger, Feb. 2006
set gpsBabelLocation to "/Applications/GPSBabelFE.app/Contents/MacOS/" -- Normal MacGPSBabel location
--set gpsBabelLocation to ""
set inputTYPE to "gpx" -- set the input file type to whatever you want
set outputTYPE to "gpx" --set the output file type to whatever you want
set strPath to POSIX file "/Users/someusername/downloads/" --set the default path for file input dialog
--set inputPATH to "~/Desktop/route.gpx" --set the path to where your input file is
-- comment out the following line if you want to use the line above
set inputPATHalias to (choose file with prompt "Select a GPX file to convert to " & outputTYPE & ":" default location strPath)
-- set inputPATH to quoted form of POSIX path of inputPATHalias -- got error, but two step below works.
set inputfilename to (inputPATHalias as text)
set inputPATH to POSIX path of inputPATHalias
set inputPATH to quoted form of inputPATH -- needed to pass to shell script
--set outputPATH to "~/Desktop/yournewfile.wpt" --set the path to where your output file will be
set outputFileName to "converted." & inputTYPE & ".2." & outputTYPE
--set outputFileName to outputFileName & ".2." & outputTYPE
set outputFolderalias to choose folder with prompt "Select a folder for converted file:"
set outputPATH to fileCheckName(outputFolderalias, outputFileName)
-- See the Documentation for normal usage. http://www.gpsbabel.org/readme.html#d0e1388
-- Using the Position filter to correct a Garmin error. When the Garmin loses sight of the sattiletes, when it reconects, it puts in poitns with a lat-long equal to the last good point, but current time and elevation (mine has a barometer). Garmin: remove extraneous points recorded when out of range that have same lat and long as last good point (altitude is ignored in this filter).
set filterSetting to "" -- use this one if you don't want any Position filtering. You can leave in uncommented and any below will override it.
-- set filterSetting to " -x position " -- Default, distance=0
-- set filterSetting to " -x position,distance=1f " -- 1 foot and leave one
-- set filterSetting to " -x position,distance=1m " -- 1 meter and leave one
-- set filterSetting to " -x position,all" -- remove all duplicates
-- set filterSetting to " -x simplify,count=1000"
-- set filterSetting to " -x simplify,error=1k" -- doesnt' work, but then it's not in the manual
-- set filterSetting to ""
tell application "System Events"
activate
do shell script gpsBabelLocation & "gpsbabel " & filterSetting & "-i " & inputTYPE & " -f " & inputPATH & " -x transform,trk=rte " & " -o " & outputTYPE & " -F " & outputPATH
end tell
--Handlers. Only used once, but I've used them elsewhere
on fileCheckName(outputFolderalias, outputFileName)
set outputFolder to POSIX path of outputFolderalias
set outputPATHnoQuote to outputFolder & "/" & outputFileName -- may need to change this if the extension isn't the same as the outputType, The Desktop is a common location
set outputPATH to quoted form of outputPATHnoQuote -- needed to pass to shell script
--check if file already exist and if we want to overwrite it
set outputFolderaliasText to outputFolderalias as text
set outputPATHcolon to outputFolderaliasText & outputFileName
tell application "Finder" -- trying to get handler to work
if file outputPATHcolon exists then display dialog "The file " & outputFileName & " already exists. Do you want to overwrite it?"
end tell
return outputPATH
end fileCheckName
--end script
I'm unable to find Applescript code that translates the filename from a prompt into a variable.
I recommend to not use the Finder.app at all for this task. Especially, checking file existence with the Posix file coercion inside the tell block is a big mistake. The Finder is also not needed to get the file basename. For this task, with the help of other experienced users, I developed a high-speed handler, provided here.
In general, I recommend using the Finder only when absolutely necessary, because it is often busy in the background with other time-consuming tasks.
set gpsBabelLocation to "/Applications/GPSBabelFE.app/Contents/MacOS/" -- Normal MacGPSBabel location
set inputType to "gpx" -- the input file type extension
set outputType to "gpx" -- the output file type extension
set defaultPath to (path to downloads folder)
set inputPath to (choose file of type inputType with prompt "Select a " & inputType & " file to convert to " & outputType & ":" default location defaultPath) -- remove 'of type inputType' to select any file
set outputFileName to getBaseName(POSIX path of inputPath) & ".2." & outputType -- the converted name
set outputFolder to choose folder with prompt "Select a folder for the converted file:"
set outputPath to fileCheckName(outputFolder, outputFileName)
set filterSetting to ""
set inputPath to quoted form of (POSIX path of inputPath)
set command to gpsBabelLocation & "gpsbabel " & filterSetting & "-i " & inputType & " -f " & inputPath & " -x transform,trk=rte " & " -o " & outputType & " -F " & outputPath
log command
if gpsBabelLocation is not "" then
do shell script command
log result
end if
on getBaseName(posixPath)
set {ATID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, "/"}
if (posixPath ends with "/") then
set baseName to text item -2 of posixPath
else
set baseName to text item -1 of posixPath
end if
if (baseName contains ".") then
set AppleScript's text item delimiters to "."
set baseName to text 1 thru text item -2 of baseName
end if
set AppleScript's text item delimiters to ATID
return baseName
end getBaseName
on fileCheckName(outputFolder, outputFileName) -- check if file exists
try
alias (outputFolder & outputFileName)
display alert quoted form of outputFileName & " already exists. Do you want to replace it?" message "A file or folder with the same name already exists at " & quoted form of POSIX path of outputFolder & ". Replacing it will overwrite its current contents." buttons {"OK", "Cancel"}
if button returned of the result is "Cancel" then error number -128 -- alert doesn't automatically cancel
end try
return quoted form of ((POSIX path of outputFolder) & outputFileName) -- quote for the shell script
end fileCheckName
Finder or System Events can be used to get file names, you just need to be a little careful when using the Finder, since it doesn't know that much about POSIX paths. With the various quoting for the shell, you also need to manipulate the various name pieces before quoting. Shortened and cleaned up a bit, your script would be something like:
--Based on the script by Robert Nixon, http://www.gpsbabel.org/os/OSX_oneclick.html
-- set path for gpsbabel as needed:
-- set gpsBabelLocation to "/opt/local/var/db/dports/software/gpsbabel/1.2.7_0/opt/local/bin/" -- DarwinPorts Default for Tiger, Feb. 2006
set gpsBabelLocation to "/Applications/GPSBabelFE.app/Contents/MacOS/" -- Normal MacGPSBabel location
-- set gpsBabelLocation to "" -- testing, etc
set inputType to "gpx" -- the input file type extension
set outputType to "gpx" -- the output file type extension
set defaultPath to (path to downloads folder)
set inputPath to (choose file of type inputType with prompt "Select a " & inputType & " file to convert to " & outputType & ":" default location defaultPath) -- remove 'of type inputType' to select any file
tell application "Finder" to set {inputName, inputExt} to {name, name extension} of inputPath
if inputExt is not "" then set inputName to text 1 thru -((count inputExt) + 2) of inputName -- just the name part
set inputPath to quoted form of POSIX path of inputPath -- quote for the shell script
set outputFileName to inputName & ".2." & outputType -- the converted name
set outputFolder to choose folder with prompt "Select a folder for the converted file:"
set outputPath to fileCheckName(outputFolder, outputFileName)
-- See the Documentation for normal usage. http://www.gpsbabel.org/readme.html#d0e1388
set filterSetting to "" -- uncomment any below to override no position filtering
-- set filterSetting to " -x position " -- Default, distance=0
-- set filterSetting to " -x position,distance=1f " -- 1 foot and leave one
-- set filterSetting to " -x position,distance=1m " -- 1 meter and leave one
-- set filterSetting to " -x position,all" -- remove all duplicates
-- set filterSetting to " -x simplify,count=1000"
set command to gpsBabelLocation & "gpsbabel " & filterSetting & "-i " & inputType & " -f " & inputPath & " -x transform,trk=rte " & " -o " & outputType & " -F " & outputPath
log command
if gpsBabelLocation is not "" then
do shell script command
log result
end if
on fileCheckName(outputFolder, outputFileName) -- check if file exists
set outputPath to (POSIX path of outputFolder) & outputFileName
tell application "Finder" to if (outputPath as POSIX file) exists then -- match the save alert
display alert quoted form of outputFileName & " already exists. Do you want to replace it?" message "A file or folder with the same name already exists at " & quoted form of POSIX path of outputFolder & ". Replacing it will overwrite its current contents." buttons {"OK", "Cancel"}
if button returned of the result is "Cancel" then error number -128 -- alert doesn't automatically cancel
end if
return quoted form of outputPath -- quote for the shell script
end fileCheckName
Related
I am trying to copy a folder on a Google Team Drive to another location, but my script keeps getting an error. The full script is below.
I basically want to copy an Excel file "Google Drive:Team Drives:Company -Sync Folder:0000-1_E.xlsx" to a location that is defined by the script.
The offending line is:
duplicate file "Google Drive:Team Drives:Company -Sync Folder:0000-1_E.xlsx" of startup disk to folder (jobNum & " Documents") of newJobFolder
Any help?
global jobNum
global newJobFolder
set jobNum to text returned of (display dialog "Enter a job number:" default answer "")
set jobName to text returned of (display dialog "Enter a job name:" default answer "")
set jobMgr to text returned of (display dialog "Enter account manager email:" default answer "")
set folderpath to (choose folder with prompt "Select client folder")
set newJobFolder to my newFold(jobNum, jobName, folderpath, jobMgr)
on newFold(theNumber, theName, thefolder, jobMgr)
set emailAddress to jobMgr
set emailSubject to theNumber & " -" & theName
set bodyText to ""
set emailLinkFileName to theNumber & " -" & theName
set subNameList to {"Designs", "Documents", "Received"}
set itemCount to count of subNameList
set linkBody to "mailto:" & emailAddress & "?subject=" & my replace_chars(emailSubject, " ", "%20") & "&body=" & my replace_chars(bodyText, " ", "%20")
tell application "Finder"
set newJobFolder to (make new folder at thefolder with properties ¬
{name:theNumber & " " & theName})
repeat with i from 1 to itemCount
set aSubFolder to make new folder at newJobFolder with properties {name:jobNum & " " & item i of subNameList}
set theMailto to make new internet location file to linkBody at aSubFolder with properties {name:emailLinkFileName, name extension:"mailloc"}
set the name extension of theMailto to "mailloc"
end repeat
duplicate file "Google Drive:Team Drives:Company -Sync Folder:0000-1_E.xlsx" of startup disk to folder (jobNum & " Documents") of newJobFolder
set name of the result to jobNum & " E.xlsx"
set theMailto to make new internet location file to linkBody at newJobFolder with properties {name:emailLinkFileName, name extension:"mailloc"}
set the name extension of theMailto to "mailloc"
end tell
end newFold
-- Generic find and replace functionality
on replace_chars(this_text, search_string, replacement_string)
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 ""
return this_text
end replace_chars
Assuming that your "Google Drive" folder resides directly in your home folder...
Try changing this...
duplicate file "Google Drive:Team Drives:Company -Sync Folder:0000-1_E.xlsx" of startup disk to folder (jobNum & " Documents") of newJobFolder
To this...
set theFile to (path to home folder as text) & "Google Drive:Team Drives:Company -Sync Folder:0000-1_E.xlsx"
duplicate file theFile to folder (jobNum & " Documents") of newJobFolder
And if that does not work, You can try this approach...
set theFile to (choose file) as alias as text
duplicate file theFile to folder (jobNum & " Documents") of newJobFolder
Then after you run it once, comment out the choose file command.
If you're using Google Drive File Stream, which is the one for businesses, the mounted drive can be reached through the user folder, the path is something like this:
"/Users/nameofuser/Google Drive File Stream/My Drive/Companyfolder"
Use this format to get to the folders and it should work, that's what I do.
I am trying to write an AppleScript to set my desktop background to the most recent NASA image of the day. I am trying to do this using this RSS feed: https://www.nasa.gov/rss/dyn/lg_image_of_the_day.rss
The last piece of the puzzle is parsing the URL of the image from the rss feed. I assume this should be very possible using grep, but I don't know how to use grep. I did look through the feed, and I know that the URL I want will be the first <link> in the first <item>.
set {year:y, month:m, day:d} to (current date)
set todaydate to d & "\\ " & m & "\\ " & y
log todaydate
set myFile to "/Users/me/Pictures/NASA\\ Image\\ of\\ the\\ Day/" & todaydate & ".jpg"
property RSSURL : "https://www.nasa.gov/rss/dyn/lg_image_of_the_day.rss"
--get the first download link from the rss feed
--ie stuff inside <link> </link> directly after first <item>
set pictureURL to "" --but to the right thing, of course
do shell script "curl -o " & myFile & " " & pictureURL
tell application "Finder" to set desktop picture to POSIX file "myFile"
Victory!!
set {year:y, month:m, day:d} to (current date)
set todaydate to d & "_" & m & "_" & y
log todaydate
set dir to "~/Pictures/NASA_image_of_the_day/"
set myFile to dir & todaydate & ".jpg"
property RSSURL : "https://www.nasa.gov/rss/dyn/lg_image_of_the_day.rss"
set XMLfile to dir & "feed.xml"
do shell script "curl -o " & XMLfile & " " & RSSURL
tell application "System Events"
tell XML file XMLfile
tell XML element "rss"
tell XML element "channel"
tell XML element "item"
tell XML element "enclosure"
set pictureURL to value of XML attribute "url"
end tell
end tell
end tell
end tell
end tell
end tell
--display dialog pictureURL
--display dialog myFile
do shell script "curl -o " & myFile & " " & pictureURL & " -L"
tell application "System Events"
tell every desktop
set picture to myFile
end tell
end tell
Am writing Applescript to take a list of folders, compress them to .zip files, and transfer the spotlight comment and label from the folder to the new file.
Thank you to CRGreen for the suggestion. Here is the final script.
on run {input, parameters}
tell application "Finder"
set theItems to selection
repeat with i from 1 to (count of theItems)
set theItem to (item i of theItems) as alias
set itemPath to quoted form of POSIX path of theItem
set theParent to POSIX path of (container of theItem as alias)
set fileName to theParent & (name of theItem) & ".zip"
set zipFile to quoted form of fileName
do shell script "zip -jr " & zipFile & " " & itemPath
do shell script "setfile -a E " & zipFile
set newItem to POSIX file fileName as alias
set comment of newItem to (get comment of theItem)
set label index of newItem to (get label index of theItem)
set oldFolder to quoted form of (theParent & name of theItem)
do shell script "rm -rf " & oldFolder
end repeat
end tell
return input
end run
The magic of parentheses! (and alias coercion):
set comment of ((POSIX file newItem) as alias) to theComment
set label index of ((POSIX file newItem) as alias) to theLabel
)
I want to write an apple-script which collect the color profile of an image.. can anyone please help me out how to do this? I've no idea!!
Thanks in advance.
I like using ExifTool by Phil Harvey to extract metadata. Here is a service I wrote to access the metadata quickly.
on run {input, parameters}
-- creates a metadata folder in the Documents folder to store results
set thePath to POSIX path of (path to documents folder) & "metadata" & "/"
do shell script "mkdir -p " & quoted form of POSIX path of thePath
set {inputFiles, outputFiles} to {{}, {}}
repeat with anItem in input
set end of inputFiles to quoted form of POSIX path of (anItem as text)
tell application "Finder" to set {name:fileName, name extension:nameExtension} to anItem
set baseName to text 1 thru ((get offset of "." & nameExtension in fileName) - 1) of fileName
set end of outputFiles to quoted form of (thePath & baseName & ".txt")
end repeat
set {TID, text item delimiters} to {text item delimiters, space}
set {inputFiles, outputFiles} to {(inputFiles as text), (outputFiles as text)}
set text item delimiters to TID
do shell script "exiftool -a " & inputFiles & " -w " & quoted form of (thePath & "%f.txt" as text) & "; open " & outputFiles
end run
In the past I had created an applescript for datedspace but which is not running anymore.
I would like to create an applescript that would look inside a folder ~/Documents/pool/ or ~/Downloads.
Let's say we are on February 7, 2011.
Check if the ~/Documents/2011/02/07/ exists
If not create ~/Documents/2011/02/07/
Move the files and/or folders inside ~/Documents/pool/ to ~/Documents/2011/02/07/
Bonus
Create a text file in ~/Documents/2011/ with the name index.mdown and containing the following format
# Index 2011
## January
[…]
## February
* 2011-02-07: Foo.jpeg
* 2011-02-07: Bar/
Lead or incomplete solutions are welcome.
Previous script
-- Script to automaticaly save documents in a date space.
-- Karl Dubost - http://www.la-grange.net/ - <karl#*******> - 2001 ©
-- Feel free to distribute it and modify it
-- Feel free to send me improvements
-- ********************************************************
-- Version 1.1 2001-03-30
-- Add control on existence of folders year and month
-- Make it more general based on Startup Disk
-- Version 1.0 2001-03-29
-- Creation of the code
-- Thanks to Bill Briggs
-- http://maccentral.macworld.com/columns/briggs.shtml
-- ********************************************************
on adding folder items to this_folder after receiving added_items
tell application "Finder"
set yourDisk to name of startup disk as string
end tell
set todaysDate to (current date)
set {d, m, y} to {day, month, year} of todaysDate
set monthList to {January, February, March, April, May, June, ¬
July, August, September, October, November, December}
repeat with i from 1 to 12
if m = (item i of monthList) then
set monthString to text -2 thru -1 of ("0" & i)
exit repeat
end if
end repeat
set y to y as string
set dayString to text -2 thru -1 of ("0" & d)
set dayString to dayString as string
set datedFolder to yourDisk & ":Documents:" & y & ":" & monthString & ":" & dayString & ":" as string
set monthFolder to yourDisk & ":Documents:" & y & ":" & monthString & ":" as string
set yearFolder to yourDisk & ":Documents:" & y & ":" as string
set rootFolder to yourDisk & ":Documents:" as string
tell application "Finder"
if (folder datedFolder exists) then
repeat with oneFile in added_items
move oneFile to folder datedFolder
end repeat
else if not (folder yearFolder exists) then
make new folder at folder rootFolder with properties {name:y}
else if not (folder monthFolder exists) then
make new folder at folder yearFolder with properties {name:monthString}
else
make new folder at folder monthFolder with properties {name:dayString}
repeat with oneFile in added_items
move oneFile to folder datedFolder
end repeat
end if
end tell
end adding folder items to
I hope this will be good enough :-) :
With the help of some basic command line applications it creates subfolders in your ~/Documents folder (mkdir -p: it will not overwrite existing directories!), moves files there (mv -n: not overwriting files with the same name), then creates monthly logfiles containing the names of addedItems and finally a index.mdown file with all monthly logfiles which should look like this:
2011/01/03: testfile9
2011/02/01: testfile10
2011/02/07: testfile11
Now go ahead and attach it to your folder, give it a try! (maybe uncomment baseFolder and change it to /tmp/test or something, or to POSIX path of thisFolder, if you want it to clean up the folder it´s attached to.)
property dateFormatForFolder : "+%Y/%m/%d"
property dateFormatForMonthlyLog : "+%Y/%m/"
property dateFormatForYearlyLog : "+%Y/"
on adding folder items to thisFolder after receiving addedItems
set baseFolder to POSIX path of (path to documents folder)
set todaysFolder to do shell script "/bin/date '" & dateFormatForFolder & "'"
set monthsFolder to do shell script "/bin/date '" & dateFormatForMonthlyLog & "'"
set yearsFolder to do shell script "/bin/date '" & dateFormatForYearlyLog & "'"
set fullPath to baseFolder & todaysFolder
createFolder(fullPath)
repeat with i from 1 to number of items in addedItems
set oneItemsPath to (quoted form of POSIX path of item i of addedItems)
try
moveToFolder(fullPath, oneItemsPath)
end try
set fileName to name of (info for item i of addedItems)
set logThis to todaysFolder & ": " & fileName
do shell script "echo " & logThis & " >> " & baseFolder & monthsFolder & "log.txt"
end repeat
do shell script "find " & baseFolder & yearsFolder & " -type f -name 'log.txt' -print0 | xargs -0 cat > " & baseFolder & yearsFolder & "index.mdown"
end adding folder items to
on createFolder(fullPath)
do shell script "/bin/mkdir -p " & quoted form of fullPath
end createFolder
on moveToFolder(fullPath, oneItemsPath)
do shell script "/bin/mv -n " & oneItemsPath & " " & fullPath
end moveToFolder