I am trying to build an applescript which will open show all files tagged with the school class I am currently in, based on current time. For instance, if the time is 10 AM on a Tuesday, it will show all my files tagged with Chemistry. Now, I have made the AppleScript to get the correct name of the class.
Now I need to tell Finder to open the files with the correct tags. How would I do this?
Basicaly, something like this:
set tagged to "Tag:Chemistry"
tell application "Finder"
reveal tagged
activate
end tell
Ofcourse, tagged here would be dynamically assigned.
The way way I would do this in the GUI is with Smart Folders. Go in the Finder, click on File->New Smart Folder and a new Finder window appears. Click on + at the top right beside Save and change Kind at top left of window to Tags. Beside Tags choose contains and then type Chemistry. Click Save at top right and call it Chemistry Stuff and allow it to be added to the side-bar. Then it will appear on the left of all Finder windows.
In the shell/Terminal, where I usually reside, I use tag for that purpose. I installed it with homebrew using brew install tag. Then I can do tag -f sometag and it lists all the files that are tagged sometag.
tag - A tool for manipulating and querying file tags.
usage:
tag -a | --add <tags> <file>... Add tags to file
tag -r | --remove <tags> <file>... Remove tags from file
tag -s | --set <tags> <file>... Set tags on file
tag -m | --match <tags> <file>... Display files with matching tags
tag -l | --list <file>... List the tags on file
tag -f | --find <tags> Find all files with tags
<tags> is a comma-separated list of tag names; use * to match/find any tag.
additional options:
-v | --version Display version
-h | --help Display this help
-n | --name Turn on filename display in output (default)
-N | --no-name Turn off filename display in output (list, find, match)
-t | --tags Turn on tags display in output (find, match)
-T | --no-tags Turn off tags display in output (list)
-g | --garrulous Display tags each on own line (list, find, match)
-G | --no-garrulous Display tags comma-separated after filename (default)
-H | --home Find tagged files only in user home directory
-L | --local Find tagged files only in home + local filesystems (default)
-R | --network Find tagged files in home + local + network filesystems
-0 | --nul Terminate lines with NUL (\0) for use with xargs -0
You can use the GUI Scripting to click on left-pane in the finder window.
Because this script use GUI Scripting to control the user-interface, you must add the applet to an approval list, displayed in the Security & Privacy system preference pane.
set tagName to "Chemistry" -- the full tag's name
my showFinderWindow(tagName)
on showFinderWindow(thisTag)
tell application "Finder" to if not (exists Finder window 1) then make new Finder window
tell application "System Events"
tell process "Finder"
repeat with i in windows
tell outline 1 of scroll area 1 of splitter group 1 of i to if exists then
tell (first row whose value of its static text 1 is thisTag) to if exists then perform action "AXOpen" of static text 1
exit repeat
end if
end repeat
end tell
end tell
end showFinderWindow
You can use the command line tool "mdfind" to search for tagged files using "kMDItemUserTags". So that's how I would find the tagged files.
The other part of your problem is finding the proper tag for the current time-of-day. I would use applescript records for this. For example you can make a record like this:
{theTag:"Chemistry", startTime:date ("10:00 AM"), endTime:date ("11:00 AM")}
So if you make a list of records you can loop through them and compare the start and end times of each record in the list to the current date.
Finally, once you have that and assuming you found some files with mdfind then you can just loop through the found files and ask the Finder to open them.
Try this. Note you have to supply your values for "requirementsRecords" and "searchFolder" in the user variables section.
-- user variables
set requirementsRecords to {{theTag:"Chemistry", startTime:date ("10:00 AM"), endTime:date ("11:00 AM")}, {theTag:"Math", startTime:date ("11:00 AM"), endTime:date ("12:00 PM")}}
set searchFolder to path to desktop
-- find the tag information given the current time
set now to current date
set thisTag to missing value
repeat with i from 1 to count of requirementsRecords
set thisRecord to item i of requirementsRecords
set thisStartTime to startTime of thisRecord
set thisEndTime to endTime of thisRecord
if now is greater than or equal to thisStartTime and now is less than or equal to thisEndTime then
set thisTag to theTag of thisRecord
exit repeat
end if
end repeat
if thisTag is missing value then error "Could not find a tag for the current time!"
-- search the search folder for files with the tag
set cmd to "mdfind -onlyin " & quoted form of POSIX path of searchFolder & " \"kMDItemUserTags == " & quoted form of thisTag & "\""
set resultsList to paragraphs of (do shell script cmd)
if resultsList is {} then error "Could not find any files tagged \"" & thisTag & "\" in the search folder"
-- open the found files with the Finder
repeat with anItem in resultsList
set thisFile to POSIX file anItem
tell application "Finder" to open thisFile
end repeat
Related
In my example .CSV file, I have a column A with the following values: 2,2,5,5,5. In column B are hyperlinks to corresponding files that require downloading: http://example.com/2A.pdf, http://example.com/2B.pdf, http://example.com/5A.pdf, http://example.com/5B.pdf, http://example.com/5BC.pdf. Having difficulty creating an applescript that creates the DL folder (based on the non-unique column A value) and applies the DLs of any corresponding row to the appropriate folder. Any help would be greatly appreciated! TIA.
From your description, I am assuming the CSV file looks something like this:
2, http://example.com/2A.pdf
2, http://example.com/2B.pdf
5, http://example.com/5A.pdf
5, http://example.com/5B.pdf
5, http://example.com/5BC.pdf
and that the file 2A.pdf should end up in a directory called 2.
Assuming I have interpreted this correctly, here is the AppleScript that will achieve this (replace /Path/To/Save/Folder/ with the full path to the folder where these new files and folders will be downloaded, and /Path/To/File.csv to the full path of the CSV file):
-- Note: The ending / is essential in BaseDir
set BaseDir to POSIX file "/Path/To/Save/Folder/"
set rows to every paragraph of (read "/Path/To/File.csv")
set AppleScript's text item delimiters to {"/"}
set [TopDir, BaseFolder] to [text items 1 thru -3, text item -2] of ¬
POSIX path of BaseDir
-- Create initial base folder if it doesn't exist
tell application "Finder" to if not (exists BaseDir) then ¬
make new folder in (TopDir as text as POSIX file) ¬
with properties {name:BaseFolder}
-- This will prevent EOF-related errors
-- Thanks to #user3439894 for highlighting the need for this
set rows to reverse of rows
if the number of words of the first item in rows is 0 ¬
then set rows to the rest of rows
repeat with row in rows
set [N, |url|] to [first word, text items -2 thru -1] of row
-- Create folder into which file will be downloaded
tell application "Finder" to if not (exists [BaseDir, N] as text) then ¬
make new folder in BaseDir with properties {name:N}
-- This is the shell command that downloads the file
-- e.g. "cd '/Users/CK/Desktop/example.com/5'; curl example.com/5BC.pdf \
-- remote-name --silent --show-error"
set command to ("cd " & ¬
quoted form of POSIX path of ([BaseDir, N] as text) & ¬
"; curl " & |url| as text) & ¬
" --remote-name --silent --show-error"
-- Run the shell command
do shell script command
end repeat
-- Open folder in Finder upon completion of downloads
tell application "Finder"
activate
open BaseDir
end tell
I should highlight that this is not a robust script intended for general use that would work across situations, but rather an example script that is tailored specifically to the case described. If your CSV file differs even slightly from my assumed format, errors are likely to occur.
I want to make an automator app which creates an empty file in current directory.
I did some google search and found:
http://hints.macworld.com/article.php?story=20050219134457298 and http://hints.macworld.com/article.php?story=20100509134904820
However, I want to do something more powerful.
If the specified file already exists, I want to show a warning instead of overwriting the original file, which is what one of the above link does. (The other one creates a text file using textEdit. I do not want to create text file. I want an empty file like what linux/unix does)
I already figured out how to do most of the part, but
How can check whether a file exists in current directory using applescript??
How can I concatenate two variable in applescript?
Checking if a file exists (assuming thefullpath is already set as in the referenced question):
tell application "Finder"
if exists POSIX file thefullpath then
--do something here like
display alert "Warning: the file already exists"
end if
end tell
Not sure what you mean by the second part but if you want to concatenate strings stored in var1 and var2 you could simply do
var1 & var2
Something I have been using a lot of late for this sort of thing is the command /bin/test
The test test for the existence of in this case a file
if (do shell script "/bin/test -e " & quoted form of (POSIX path of theFile) & " ; echo $?") is "1" then
-- 1 is false
--do something
end if
The -e option:
-e file True if file exists (regardless of type).
The are tons of other test options shown in the /bin/test man page
The following code, adapted from your second link, is usually right, but it doesn't always work. The current directory is better specified as the directory of the document that is being opened which is most likely from the Finder's front window, but not necessarily. I like to write code that will work no matter what.
on run {input, parameters}
tell application "Finder"
set currentPath to insertion location as text
set x to POSIX path of currentPath
display dialog "currentPath: " & (x as text)
end tell
return x
end run
I wrote a whole "Run AppleScript" action to put things into context:
on run {input, parameters}
# count the number of files
set numFiles to 0
repeat with f in input
# warn the user that folders are not processed in this app
tell application "Finder"
if (kind of f is "Folder") then
display dialog "The item: " & (f as text) & " is a folder. Only files are allowed. Do you want to continue processing files or do you want to cancel?"
else
set numFiles to numFiles + 1
end if
end tell
end repeat
# require that at least one file is being opened
if numFiles < 1 then
display alert "Error: the application Test1.app cannot be run because it requires at least one file as input"
error number -128
end if
# get the current directory from the first file
set theFirstFile to (item 1 of input)
tell application "System Events" to set theFolder to (container of theFirstFile)
# ask the user for a file name
set thefilename to text returned of (display dialog "Create file named:" default answer "filename")
# create the file
tell application "System Events" to set thefullpath to (POSIX path of theFolder) & "/" & thefilename
set theCommand to "touch \"" & thefullpath & "\""
do shell script theCommand
# return the input as the output
return input
end run
The "touch" command is OK. If the file doesn't exist, it is created and if it does exist, only the modification date is changed (which isn't too bad) but it doesn't overwrite the file. If your file is being overwritten, it's not the touch command that is doing it.
I changed the default file name to remove the extension ".txt" This extension may default to being opened by TextEdit.app, but you can change this in the Finder by choosing "Get Info" for a file and changing the "Open With" property. You can change which application opens the file with that extension or you can change them all. For example, all of my ".txt" files are opened with BBEdit.app
Will you vote my answer up?
Another option that doesn't require Finder or System Events is to try to coerce a POSIX file or file object to an alias:
try
POSIX file "/tmp/test" as alias
true
on error
false
end try
(This is a new edit from a previous question of mine which achieved -3 votes. Hope this new one has a better qualification)
I need to create an Automator service to organize a high amount of files into folders. I work with illustrator and from each .ai file I create 3 more formats: [name.pdf], [name BAJA.jpg] and [name.jpg], thats 4 files in total
My problem is that during the week I repeat this process to more than 90 different .ai files. So 90 files * 4 is 360 independent files all into the some project folder.
I want to grab all 4 related files into one folder, and set the folder name as the same as the .ai file.
Since all the file names are identical (except one), I thought of telling the finder to grab all the files with the same name, copy the name, create a folder and put this files inside, but I have a file name variant [name LOW.jpg] Maybe I can tell the script to strip that work as an exception.
That way I will all 4 the files unified into one folder.
Thank you in advance
Update: This problem was originally posted back in 2013, now I have a solution. People help me assembled this script to fit my needs.
I added this as a service and assigned a keyboard shurtcut on MacOs.
This is the code:
on run {input, parameters} -- create folders from file names and move
set output to {} -- this will be a list of the moved files
repeat with anItem in the input -- step through each item in the input
set {theContainer, theName, theExtension} to (getTheNames from anItem)
try
# check for a suffix and strip it off for the folder name
if theName ends with " BAJA" then
set destination to (makeNewFolder for (text 1 thru -6 of theName) at theContainer)
else
set destination to (makeNewFolder for theName at theContainer)
end if
tell application "Finder"
move anItem to destination
set the end of the output to the result as alias -- success
end tell
on error errorMessage -- duplicate name, permissions, etc
log errorMessage
# handle errors if desired - just skip for now
end try
end repeat
return the output -- pass on the results to following actions
end run
to getTheNames from someItem -- get a container, name, and extension from a file item
tell application "System Events" to tell disk item (someItem as text)
set theContainer to the path of the container
set {theName, theExtension} to {name, name extension}
end tell
if theExtension is not "" then
set theName to text 1 thru -((count theExtension) + 2) of theName -- just the name part
set theExtension to "." & theExtension
end if
return {theContainer, theName, theExtension}
end getTheNames
to makeNewFolder for theChild at theParent -- make a new child folder at the parent location if it doesn't already exist
set theParent to theParent as text
if theParent begins with "/" then set theParent to theParent as POSIX file as text
try
return (theParent & theChild) as alias
on error errorMessage -- no folder
log errorMessage
tell application "Finder" to make new folder at theParent with properties {name:theChild}
return the result as alias
end try
end makeNewFolder
Hope this helps.
It's a pity you get downvoted as I, personally, enjoy answering these sorts of questions, as it helps me practise and improve my own skills.
Thanks for posting your solution. I think it's a great gesture and others will find it useful.
This script is a bit shorter than and uses "System Events" instead of "Finder", so will be quicker for large numbers of files:
set IllustratorOutputFolder to "/Users/CK/Desktop/example"
tell application "System Events" to ¬
set ai_files to every file in folder IllustratorOutputFolder ¬
whose name extension is "ai"
set Output to {}
repeat with ai_file in ai_files
set AppleScript's text item delimiters to "."
get name of ai_file
get text items of result
set basename to reverse of rest of reverse of result as text
tell application "System Events"
get (every file in folder IllustratorOutputFolder ¬
whose name begins with basename)
move result to (make new folder ¬
in folder IllustratorOutputFolder ¬
with properties {name:basename})
end tell
set end of Output to result
end repeat
return Output -- list of lists of moved files
Just an alternative way of doing things. Not that it's better or worse, but just a different solution.
You could also save this as script.sh (in TextEdit in plain text mode) and run it with bash script.sh in Terminal:
cd ~/Target\ Folder/
for f in *.ai *.pdf *.jpg; do
dir=${f%.*}
dir=${dir% LOW}
mkdir -p "$dir"
mv "$f" "$dir"
done
I have a folder containing about 5000 files with names like:
Invoice 10.1 (2012) (Digital) (4-Attachments).pdf
Carbon Copy - Invoice No 02 (2010) (2 Copies) (Filed).pdf
01.Reciept #04 (Scanned-Copy).doc
I want to rename these files by removing everything from the first bracket onwards, so they look like this:
Invoice 10.1.pdf
Carbon Copy - Invoice No 02.pdf
01.Reciept #04.doc
I have found lots of scripts that will remove the last x letters, but nothing that will crop from a particular character.
Ideally I would like to use Automator, but I'm guess this might too complex for it. Any ideas?
Try:
set xxx to (choose folder)
tell application "Finder"
set yyy to every paragraph of (do shell script "ls " & POSIX path of xxx)
repeat with i from 1 to count of yyy
set theName to item i of yyy
set name of (file theName of xxx) to (do shell script "echo " & quoted form of theName & " | sed s'/ (.*)//'")
end repeat
end tell
The code posted by #adayzone will work, but there is no need to use sed for this – plain AppleScript will do, using offset:
set fullString to "Invoice 10.1 (2012) (Digital) (4-Attachments).pdf"
set trimmedString to text 1 thru ((offset of "(" in fullString) - 1) of fullString
-- trim trailing spaces
repeat while trimmedString ends with " "
set trimmedString to text 1 thru -2 of trimmedString
end repeat
this returns “Invoice 10.1". To split the file name into the name and extension, and re-add the extension, you can use System Events’ Disk-File-Folder suite, which will provide the handy name extension property you can store and re-add after trimming the name.
Assuming you use some Automator action to get the files to be processed, the full processing workflow would be to add an AppleScript action after the file selection part with the following code:
repeat with theFile in (input as list)
tell application "System Events"
set theFileAsDiskItem to disk item ((theFile as alias) as text)
set theFileExtension to name extension of theFileAsDiskItem
set fullString to name of theFileAsDiskItem
-- <insert code shown above here>
set name of theFileAsDiskItem to trimmedString & "." & theFileExtension
end tell
end repeat
If you want your Automator workflow to process the files any further, you will also have to create a list of aliases to the renamed files and return that from the AppleScript action (instead of input, which, of course, is not valid anymore).
I made this Applescript script to create symbolic links.
Appart from POSIX path of, how can I get the file name, without the path, of the dropped file?
on open filelist
repeat with i in filelist
do shell script "ln -s " & POSIX path of i & " /Users/me/Desktop/symlink"
end repeat
end open
PS: I know this expects many files to be dropped and tries to create many links with the same name, which gives an error. Actually I copied this example from a website and as I don't know almost anything about Applescript, I don't know how to do this for a single file, help on that would be appreciated too.
I'm not sure what precisely you're trying to do, but I have a guess. Is the idea that you want to take every file dropped on the script and create a symbolic link to each one on the Desktop? So if I drop ~/look/at/me and ~/an/example, you'll have ~/Desktop/me and ~/Desktop/example? If that's what you want, then you're in luck: ln -s <file1> <file2> ... <directory> does exactly that. (Edit: Although you have to watch out for the two-argument case.) Thus, your code could look like this:
-- EDITED: Added the conditional setting of `dest` to prevent errors in the
-- two-arguments-to-ln case (see my comment).
on quoted(f)
return quoted form of POSIX path of f
end quoted
on open filelist
if filelist is {} then return
set dest to missing value
if (count of filelist) is 1 then
tell application "System Events" to set n to the name of item 1 of filelist
set dest to (path to desktop as string) & n
else
set dest to path to desktop
end if
set cmd to "ln -s"
repeat with f in filelist & dest
set cmd to cmd & " " & quoted(f)
end repeat
do shell script cmd
end open
Note the use of quoted form of; it wraps its argument in single quotes so executing in in the shell won't do anything funny.
If you want to get at the name of the file for another reason, you don't need to call out to the Finder; you can use System Events instead:
tell application "System Events" to get name of myAlias
will return the name of the file stored in myAlias.
Edit: If you want to do something to a single file, it's pretty easy. Instead of using repeat to iterate over every file, just perform the same action on the first file, accessed by item 1 of theList. So in this case, you might want something like this:
-- EDITED: Fixed the "linking a directory" case (see my comment).
on quoted(f)
return quoted form of POSIX path of f
end quoted
on open filelist
if filelist is {} then return
set f to item 1 of filelist
tell application "System Events" to set n to the name of f
do shell script "ln -s " & ¬
quoted(f) & " " & quoted((path to desktop as string) & n)
end open
It's pretty much the same, but we grab the first item in filelist and ignore the rest. Additionally, at the end, we display a dialog containing the name of the symlink, so the user knows what just happened.
As an example, you can work with the Finder instead of a shell script to get the name of a single file that is dropped on the script that is saved as an application. If you don't need the display dialog, you can remove it, but you have the file name as a variable to work with:
on open the_files
repeat with i from 1 to the count of the_files
tell application "Finder"
set myFileName to name of (item i of the_files)
end tell
display dialog "The file's name is " & myFileName
end repeat
end open