applescript to shell - shell

I have created a small applescript that looks for files that match multiple strings in a certain folder, and when they are found, it returns the path to that file. in applescript language, it looks like this:
set filesExist to path of (every file in folder pathUnsorted whose name starts with (item 1 of theWords) and name contains (item 2 of theWords) and name contains (item 3 of theWords) and name contains (item 4 of theWords) and name contains (item 5 of theWords))
now, I need to convert this to a shell command, since those can run inside applescript with this command:
set filesExist to do shell script "(shell command goes here)"
Unfortunately I have no idea how to do it in a shell command...can someone help me??

Assuming that pathUnsorted is already a POSIX path:
do shell script "ls " & quoted form of (pathUnsorted & "/" & (item 1 of theWords)) & "*" & ¬
" | grep " & quoted form of (item 2 of theWords) & ¬
" | grep " & quoted form of (item 3 of theWords) & ¬
" | grep " & quoted form of (item 4 of theWords) & ¬
" | grep " & quoted form of (item 5 of theWords)
It’s theoretically possible to construct a regular expression that would match all the right files in one shot, but this is simpler.

Related

Applescript - Creating folders based on the first word of the filename

Essentially i'm looking for an applescript that allow me to order the massive 50.000 files by creating folders that have just the first word of the files, ignoring the rest of the filename after the first space.
For eaxmple the 50.000 files are named like this:
- amazingfrog -shootingbase.jpg
- frog 2sHDn1_9fFs12s.jpg
- frog 29adjjdd39939.mov
- Horse IUS39aosdja.mov
- horse 282131888.jpg
- HORSE.jpg
And so on.....
- I would like to be like this:
- amazingfrog
-amazingfrog -shootingbase.jpg
- frog
-frog 2sHDn1_9fFs12s.jpg
-frog 29adjjdd39939.mov
- horse
-horse IUS39aosdja.mov
-horse 282131888.jpg
-horse.gif
And so on....
On the internet i came across with the following script:
set chosenFolder to (choose folder)
tell application "Finder" to set fileList to files of chosenFolder
repeat with aFile in fileList
set {name:Nm, name extension:Ex} to info for (aFile as alias)
if Ex is missing value then set Ex to ""
if Ex is not "" then set Nm to text 1 thru ((count Nm) - (count Ex) - 1) of Nm
set dateFolder to text 1 thru 15 of Nm
set sourceFile to quoted form of POSIX path of (aFile as text)
set destinationFile to quoted form of (POSIX path of chosenFolder & dateFolder & "/" & name of aFile)
do shell script "ditto " & sourceFile & space & destinationFile
do shell script "rm " & sourceFile
end repeat
The only problem is that i have to choose in the "text 1 thru" the numbers of the letters i want to keep. And unfortunately the first word of the filenames have different length...
Could be possible to modify this script to my needed? or do you have any other suggestions?
Thanks in advance for any reply!!
I recommend to use text item delimiters to extract the first part of the file name
set chosenFolder to (choose folder)
tell application "Finder" to set fileList to files of chosenFolder
set TID to text item delimiters
set text item delimiters to space
repeat with aFile in fileList
set fileName to name of aFile
set textItems to text items of fileName
if (count textItems) = 1 then
set fileExtension to name extension of aFile
set folderName to text 1 thru ((get offset of "." & fileExtension in fileName) - 1) of fileName
else
set folderName to first item of textItems
end if
set sourceFile to quoted form of POSIX path of (aFile as text)
set destinationFile to quoted form of (POSIX path of chosenFolder & folderName & "/" & fileName)
do shell script "ditto " & sourceFile & space & destinationFile
do shell script "rm " & sourceFile
end repeat
set text item delimiters to TID

Get path to main iTunes library and play a song from it

I currently have an Applescript that lets you type in a song and play it.
Here it is:
set userInput to text returned of (display dialog "Type something" default answer "")
if userInput contains "Play " then
set {TID, text item delimiters} to {text item delimiters, {"Play "}}
if length of userInput is greater than or equal to 2 then set resultString to text item 2 of userInput
set text item delimiters to TID
set playSong to (resultString as string)
tell application "iTunes"
set mySongs to every track of library playlist 1 whose name is playSong
repeat with aSong in mySongs
play aSong
end repeat
if (count of mySongs) = 0 then
say "Song not found"
end if
end tell
end if
Basically, I need to get the path to the main iTunes library and play a song from it. Currently, to search for songs, iTunes has to open. And if it can't find the song, it just stays open. I want to search the actual iTunes directory to make it so if iTunes cannot find a song, it doesn't open
I have no idea how to do this.
Thanks
Here is the script to search in the "iTunes Library.xml" file.
set XMLFile to my get_iTunes_Library_xml()
set userInput to text returned of (display dialog "Type something" default answer "Play ")
if userInput begins with "Play " and length of userInput > 5 then
set playSong to text 6 thru -1 of userInput
set searchString to "<key>Name<\\/key><string>" & playSong & "<\\/string>" -- to match exact name
if (my searchTrackName(searchString, XMLFile)) is not "" then
tell application "iTunes" to play (tracks whose name is playSong)
else
say "Song not found"
end if
end if
on searchTrackName(t, f) -- search in iTunes Library.xml file
if "&" is in t then set t to do shell script "sed \"s/&/&/g\" <<<" & quoted form of t -- to replace "&" by "&"
try -- return a count of matching lines
return do shell script "grep -c -m1 -i " & (quoted form of t) & " " & f -- "-i" equal case insensitive, "-m 1" to exit at first match
end try
return ""
end searchTrackName
on get_iTunes_Library_xml() -- get the path
do shell script "defaults read com.apple.iApps iTunesRecentDatabases | sed -En 's:^ *\"(.*)\"$:\\1:p' |/usr/bin/perl -MURI -e 'print URI->new(<>)->file;'"
return quoted form of the result
end get_iTunes_Library_xml
The "com.apple.iApps.plist" file contains the path to yours iTunes libraries (if you have more than one), the script get the path of the "iTunes Library.xml" file of the current library.
Not a finished solution, but perhaps a starting point.
I didn't find a way to get automatically the path to the iTunes library.
With the StandardAdditions you can get the path to the main music folder in the home folder via
set searchPath to POSIX path of music folder
You can set the path manual, like this:
set searchPath to quoted form of "/Users/USERNAME/Music/iTunes/iTunes Music/"
To search for the music files without iTunes, i use the shell command "mdfind"
do shell script "mdfind -count -onlyin PATH SEARCHSTRING"
With the count-Flag we get the total numbers of matches. If you like to see what mdfind finds, omit the count-Flag.
tell application "System Events"
set userInput to text returned of (display dialog "Search for music" default answer "madonna")
set searchPath to POSIX path of music folder
end tell
set shellCommand to "mdfind -count -onlyin " & searchPath & " " & quoted form of userInput
set searchResult to (do shell script shellCommand) as number
if searchResult = 0 then
say "Song not found"
else if searchResult >= 1 then
say "Found some songs"
end if
With mdfind you can search in the metadata, for example you can search for only MP3-Files:
mdfind "kMDItemContentType=='public.mp3'"

Move Files X Per Folder

I've put a script together that moves a predefined number of files into folders that are created sequentially.
It seems somewhat sluggish and being new to this I'm wondering if there's a more elegant do shell script command to aid in this.
set filesPerFolder to 100
set zeroPad to 3
tell application "Finder" to set chosenFolder to (target of Finder window 1) as text
set thisDir to POSIX path of chosenFolder
set folderCount to 1
repeat
set folderCount to zero_pad(folderCount, zeroPad)
set filesToMove to (do shell script "ls -1 " & thisDir & " | wc -l") as integer
if filesToMove is 0 then
return
end if
set theNewFolder to thisDir & folderCount
set asDir to POSIX file theNewFolder
tell application "Finder"
if exists asDir then
-- do nothing
else
do shell script "mkdir -p " & theNewFolder
end if
end tell
tell application "Finder" to set firstFile to first file of folder chosenFolder as alias
set fileToMove to POSIX path of firstFile
set theMove to quoted form of fileToMove & " '" & theNewFolder & "/'"
do shell script "mv -f " & theMove
set filesInFolder to (do shell script "ls -1 " & theNewFolder & " | wc -l") as integer
if filesInFolder ≥ 10 then
set folderCount to folderCount + 1
end if
end repeat
on zero_pad(value, string_length)
set string_zeroes to ""
set digits_to_pad to string_length - (length of (value as string))
if digits_to_pad > 0 then
repeat digits_to_pad times
set string_zeroes to string_zeroes & "0" as string
end repeat
end if
set padded_value to string_zeroes & value as string
return padded_value
end zero_pad
Thanks to Lri's shell command the script is leaner and efficient.
tell application "Finder" to set thisDir to (target of Finder window 1) as string
set rootDirectory to quoted form of POSIX path of thisDir
set counTed to (do shell script "ls -1 " & rootDirectory & " | wc -l") as integer
set filesToMove to (do shell script "ls -2 " & rootDirectory & " | wc -l") as integer
if filesToMove is 0 then
display alert "There are no files in the root of this directory to move."
return
end if
set filesPerFolder to text returned of (display dialog "There are " & counTed & " files in this folder.
How many files would you like to move per folder: " default answer "100")
set fileCount to (do shell script "cd " & rootDirectory & " && i=0;for f in *;do d=$(printf %03d $((i/" & filesPerFolder & "+1)));let i++;mkdir -p $d;mv \"$f\" $d;done")
set filesLeft to (do shell script "ls -2 " & rootDirectory & " | wc -l") as integer
if filesLeft is 0 then
display alert "Completed."
return
end if
i=0;for f in *;do d=$(printf %03d $((i/100+1)));let i++;mkdir -p $d;mv "$f" $d;done
Or using GNU parallel:
ls|parallel -k -N100 x=\$\(printf %03d {#}\)\;mkdir -p \$x\;mv {} \$x
-k keeps the order of the lines and {#} is the sequence number.

Read folder, parse filenames and call other program

In brief, I need to do something like this:
I have a folder with a lot of files and want to process all files with extension .epub.
All files already follow a naming scheme: Lastname, Firstname - Title.epub or Lastname, Firstname - Series x - Title.epub and I need a parser for Lastname, Firstname, Series (if existing) and Title.
I have a command-line tool that sets metadata: ebook-meta filename -a "Firstname Lastname" -t Title
There are many snipplets for 1.), however I am in need for input for 2.) and appreciate any help/pointers!
You can start with the following and change it to meet your needs. It compiles, although untested.
set p to POSIX file "/Users/kaass/Desktop/test/"
tell application "Finder" to set filelist to name of every file of folder p
repeat with filename in filelist
set text item delimiters to ""
if text -5 thru -1 of filename is equal to ".epub" then
set temp to items 1 thru -6 of filename as text
set text item delimiters to " - "
set myWord to text items 1 thru -1 of temp
set title to myWord's last item as text
if myWord's length is equal to 3 then set series to myWord's second item as text
set myWord to item 1 of myWord as text
if myWord contains "," then
set text item delimiters to ", "
else
set text item delimiters to " "
end if
set author to (text item 2 of myWord) & space & (text item 1 of myWord)
set path_and_filename to POSIX path of file p & filename
do shell script "echo Processing file " & quoted form of path_and_filename & ": " & author & " +++ " & title
do shell script "/Applications/calibre.app/Contents/MacOS/ebook-meta " & quoted form of path_and_filename & " -a " & quoted form of author & " -t " & quoted form of title
end if
end repeat
Just comment if you need something to be changed.

Script to manage dated space on Mac OS X (10.6) for downloads

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

Resources