Basic applescripting - reading multiple files within folder - applescript

I've been trying to find something that explains how to read multiple files in applescript but I can only find ones that read 1 file.
read all text files (.js, .json, .css, etc) within a folder
verify each has a specific copyright (e.g. "© 2013 copyright. All rights reserved.")
create a new document that lists the file and whether the copyright is correct for each.
e.g.
particleTrail.js - PASS
blur.js - PASS
canvasParticle.js - FAIL
etc...
Thanks!

set output to ""
tell application "Finder"
repeat with f in (get files of (get POSIX file "/Users/username/Folder" as alias))
if (read (f as alias) as «class utf8») contains "© 2013 copyright" then
set output to output & name of f & " - PASS" & linefeed
else
set output to output & name of f & " - FAIL" & linefeed
end if
end repeat
end tell
set b to open for access "/Users/username/Desktop/output.txt" with write permission
set eof b to 0
write output to b as «class utf8»
close access b
If as «class utf8» is left out, read and write use the primary encoding, like MacRoman or MacJapanese. Unicode text is UTF-16.
Or using shell scripting:
for f in ~/Folder/*; do grep -q '© 2013 copyright' "$f" && x=PASS || x=FAIL; echo "${f##*/} - $x"; done > ~/Desktop/output.txt
grep -lv '© 2013 copyright' ~/Folder/*

Related

Renameing a bunch of quicktimes in applescript

I have a bunch of files in a folder named something like this:
123456_this_is_a_fun_test_v01.mov
685954_this_more_is_a_fun_test_v01_clean.mov
They all have a 6 digit number in the beginning and a version number somewhere. What i need to do is remove the version number and move the first 6 digits til the end, before the extension name, like this:
this_is_a_fun_test_123456.mov
this_more_is_a_fun_test_clean_685954.mov
Been trying some stuff out in automator and some simple Applescripting, but without any luck. My scripting skills are not good, I'm only at "Hobby" level. Anyone got some advice?
tell application "Finder"
--grab the selected files and put them into a variable
set F to selection
end tell
-- This will be the character used to rejoin pieces
-- of the filename after breaking them apart
set the text item delimiters to "_"
repeat with g in F -- Loop through the file list
-- Get the filename
tell application "System Events" to get name of g
-- Eliminate the version number component of the filename
set r to do shell script ¬
"echo " & quoted form of result & ¬
" | egrep -o '[^_\\.]+'" & ¬
" | egrep -iv 'v\\d+'"
-- Assemble the other components in the new order
get {paragraphs 2 thru -2, paragraph 1} of r
get (result as text) & ".mov"
-- Rename the file to the new name
tell application "System Events" to set name of g to result
end repeat
I've added comments to this AppleScript, which explain what each part of the script does. As it stands, it's designed to run from inside Script Editor, but it could easily be tweaked to be part of an Automator workflow.
Copy-n-paste the script into Script Editor. Replace /Path/To/Folder with the path to the folder in which your .mov files are located (keep the quotes). Use the full path, i.e. /Users/CK/Movies and not ~/Movies. Press Cmd+K to compile the script, and check for pre-run syntax errors, and the like. When the fonts change and the script looks all pretty-printed, then hit Cmd+R to execute it.
tell application "System Events" to get the files in folder ¬
"/Path/To/Folder" whose name extension is "mov"
set F to the result -- The list of .mov files that need renaming
-- This will be the character used to rejoin pieces
-- of the filename after breaking them apart
set the text item delimiters to "_"
repeat with g in F -- Loop through the file list
-- Get the filename
tell application "System Events" to get name of g
-- Eliminate the version number component of the filename
set r to do shell script ¬
"echo " & quoted form of result & ¬
" | egrep -o '[^_\\.]+'" & ¬
" | egrep -iv 'v\\d+'"
-- Assemble the other components in the new order
get {paragraphs 2 thru -2, paragraph 1} of r
get (result as text) & ".mov"
-- Rename the file to the new name
tell application "System Events" to set name of g to result
end repeat
With a bit of google Fu and a lot of looking at your code i got it to work on selected files. Thanks for the help
tell application "Finder"
set F to selection
end tell
set the text item delimiters to "_"
repeat with g in F -- Loop through the file list
-- Get the filename
tell application "Finder" to get name of g
-- Eliminate the version number component of the filename
set r to do shell script ¬
"echo " & quoted form of result & ¬
" | egrep -o '[^_\\.]+'" & ¬
" | egrep -iv 'v\\d+'"
-- Assemble the other components in the new order
get {paragraphs 2 thru -2, paragraph 1} of r
get (result as text) & ".mov"
-- Rename the file to the new name
tell application "Finder" to set name of g to result
end repeat
tell application "System Events"
activate
display dialog "Selected files have been renamed!"
end tell

OSX: How can check whether a file exists in current directory using applescript?

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

AppleScript to read text file containing file names, search for each file name, and if a file is found copy it to a folder

Sorry to ask a question without even pasting my coding attempt, but I've never used AppleScript before and I have no idea how I would do this. I've found bits of code online that do small parts of each step of this, but some of the key parts I can't figure out how to do. If I can get this figured out it would save a lot of time. Basically my problem is that a client sent over thousands of photos, all in multiple levels of sub folders, along with an Excel document containing about 300 file names that I need to pull out and use. I can copy the file names from the Excel document into a plain text file, either multi-line or comma separated.
So this is what I need to do:
Open folder selector dialog to select the destination folder
Open file selector dialog to select the text file
Loop through each line (or comma separated value) of the text file
Take that string and search for a file name containing the string
Copy the first result into a folder (let's say Desktop:Found Photos)
If a file could not be found matching the string then add the search string into a text file (so I could email it to the client and ask them to send it to me)
If you can't code this whole process, if you could help me with looping through the text file, searching for the file name and copying the first result to another folder, and adding the file name to a text file if a file wasn't found, then I could probably piece it it all together. Thanks for any help.
You can try something along the lines of:
set newFolder to POSIX path of (path to desktop as text) & "Found Photos"
do shell script "mkdir -p " & quoted form of newFolder
set filePaths to paragraphs of (read (choose file with prompt "Select file list") as «class utf8»)
set fileFolder to POSIX path of (choose folder with prompt "Select folder containing files")
set foundFiles to {}
repeat with fileName in filePaths
set fileName to (contents of fileName)
set xxx to do shell script "find " & quoted form of fileFolder & " -name " & quoted form of fileName
if xxx ≠ "" then
tell application "System Events" to move file xxx to newFolder
set end of foundFiles to fileName & return
end if
end repeat
set foundFiles to (foundFiles as text)
do shell script "echo " & quoted form of foundFiles & " > " & quoted form of POSIX path of ((path to desktop as text) & "FoundFiles.txt")
It might have been easier to use shell scripting:
IFS=$'\n'
mkdir -p ~/Desktop/target/
for l in $(cat ~/Desktop/files.txt); do
found=$(find ~/Documents/source -type f -name "*$l*")
[[ -n $found ]] && cp $found ~/Desktop/target/ || echo "$l"
done

Use Automator/Applescript to crop filenames after certain character?

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).

Getting the file name of files dropped on the script

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

Resources