Moving files into folders / subfolders based on file names [closed] - applescript

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
Hope someone can help me,
To start out, my AppleScript skills are almost non-existing.
I get a number of files for archiving purposes in the following format which need sorting. The format is first the device name, followed by a run number and a sample number followed by some text.
Example file: "UZLA 55879 [05x13] september cal run.cdf" (file format varies)
Which needs to be moved into a folder: ~/UZLA 55879 (LCMS)/Run 5/
The device name is fairly random, sometimes just a number sometimes the entire official naming.
The main folder has a secondary item in brackets after the device name which is not in the file name that is being moved. the string before "[" and "(" do match, after the main name it's different.
The subfolder doesn't always exist, when a new run is started the folder /Run 6/ for example might not exist. Their's no 0 padding to the numbers
The files all arrive in the same folder and their should be no other files located in that folder.
To round this of we like to make an alias in a single folder on the main drive (files are moved to external system) for direct access, which is easy for quick last think look up but entirely unwieldy for the whole system (older aliases are deleted from it by other script).
Thanks.
Okay, so this was annoyingly closed, appearance because it only helps me and not random person from the future. Getting help for me was kinda the point. This is where we're at, with thanks to adayzdone:
set myFolder to (choose folder)
tell application "System Events" to set folderName to myFolder's name
set {TID, text item delimiters} to {text item delimiters, {"(", ")"}}
set myText to text item 2 of folderName
set text item delimiters to TID
set myFiles to every paragraph of (do shell script "find " & quoted form of (POSIX path of myFolder) & " \\! -name \".*\" -type f")
repeat with aFile in myFiles
set aFile to aFile as text
tell application "Finder" to set fileName to name of (POSIX file aFile as alias)
set newPath to "~/" & quoted form of (do shell script "echo " & quoted form of fileName & " | sed -e 's/\\[0/\\[/' -e 's/\\([^\\[]*\\)\\[\\([0-9]*\\)x[0-9]*\\].*/\\1(" & myText & ")\\/Run \\2\\//'") as text
do shell script "mkdir -p " & newPath & " ; mv " & quoted form of aFile & space & newPath
end repeat
This gives the following error: error "Can’t get text item 2 of \"testFolder\"." number -1728 from text item 2 of "testFolder"
Let me clarify: I have a bunch of files in a folder named /testFolder/ (always named that, all files enter here) what I want is to move the files into folders and subfolders in a given format based on the file names.
Example: File: /UZLA 55879 [01x05] XXX.cdf
Base name "UZLA 55879", the folder /UZLA 55879 (LCMS)/ exists at the destination. the (LCMS) is irrelevant to the move, it's just extra junk on the folder name, the script should detect that the folder exists (despite what junk comes between the ()" and use it as it's destination. If no folder with that base name exist it can just pop up an error or crash the whole script, that's not really the issue as new base names are rarely created and are named manually (and rather randomly) anyway.
The second part of the name is [01x05] the first part of that, "01" is detected (stripped from its padding zero) and moved into subfolder /Run 1/ (If it's "[05x07] is goes into /Run 7/ etc. the rest of the file name/extention is irrelevant to the move.
Current issue: The script now tries to pull the info from the starting folder to choose the destination folder, the starting folder is (not) named /UZLA 55879 (LCMS)/ it uses that "LCMS" to create the destination folder. (which it can't since the starting folder is 1) not named that and 2)) every destination folder has a different item (some are the same though) between those parentheses so naming the starting folder like that is useless. The script uses " & myText & " for that, that string has to be a random string which is defined by the destination folder not the starting folder.

I would normally not answer a question like this unless the user has put some effort into it, but I am a sucker for regular expressions.
set sourceFolder to "/Users/You/Desktop/testFolder"
set destFolder to "/Users/You/Desktop/testFolder2"
set myFiles to every paragraph of (do shell script "find " & quoted form of sourceFolder & " \\! -name \".*\" -type f")
repeat with aFile in myFiles
set aFile to aFile as text
tell application "Finder" to set fileName to name of (POSIX file aFile as alias)
-- Find name of parent folder
set parentName to do shell script "echo " & quoted form of fileName & " | sed 's/ \\[.*//'"
tell application "System Events" to set parentFolder to POSIX path of (first folder of folder destFolder whose name starts with parentName)
-- Extract the text between ( and )
set myText to do shell script "echo " & quoted form of parentFolder & " | sed 's/.*(\\(.*\\)).*/\\1/'"
set newPath to quoted form of (destFolder & "/" & (do shell script "echo " & quoted form of fileName & " | sed -e 's/\\[0/\\[/' -e 's/\\([^\\[]*\\)\\[\\([0-9]*\\)x[0-9]*\\].*/\\1(" & myText & ")\\/Run \\2\\//'") as text)
do shell script "mkdir -p " & newPath & " ; mv " & quoted form of aFile & space & newPath
end repeat

Related

AppleScript: Download URL from file and keep the names

I want to create a simple AppleScript:
define a folder (that will get all the images, docs etc.)
read a file (.txt for example)
download all the URLs into the folder with their original name
Currently, my file has one URL by line, no separator.
I found several scripts but they always do something I don't want, don't need or doesn't work.
I found one that is very close to what I want, but it's editing the names in the loop.
I didn't succeed to split the URL and keep the last part.
Here it is:
property desktopPath : path to desktop as string
set n to 1
repeat with urlLine in paragraphs of (read alias (desktopPath & "filename.txt"))
set qURL to quoted form of urlLine
if qURL ≠ "''" then
set dest to quoted form of ¬
(POSIX path of desktopPath & "URLs/" & n & ".jpg")
do shell script "curl " & quoted form of urlLine & " > " & dest
set n to n + 1
end if
end repeat
If you have any other solution, I take.
Thanks in advance
I found a script that is working fine.
You just need to be sure about the txt file: the list inside should not have any text format.
Weirdly I have to do a copy/paste through a text editor to remove every text format.
1/ Put the txt file on your desktop, 2/ Create a "download" folder on your desktop, 3/ Start the script
set theList to (path to desktop as text) & "Download.txt" -- File name with the URLs
set theFolder to (path to desktop as text) & "download" -- Folder name between quotes
set theFolder to quoted form of POSIX path of theFolder
set theImages to read alias theList as list using delimiter linefeed
repeat with i from 1 to count of theImages
set thisItem to item i of theImages
do shell script "cd " & theFolder & "; " & "curl -O " & quoted form of thisItem
end repeat

Trouble with script moving files to a newly created folder in Applescript

I am having trouble with what I think is a pretty straightforward task, but cannot seem to get my script to work correctly. I have found a lot of help through the forums with regards to the individual routines used, but it still seems to fail.
In short, what I would like to do is monitor a folder for new files being added. Once a batch of files are added (every other day or so), it will create a folder in another directory with the new folder name being the current date, move those files to the new directory, and then execute a simple bash script which uses the new directory name as an argument.
My script compiles ok, but once files are added it only creates the new folder and nothing else. I appreciate any help.
property the_sep : "-"
on adding folder items to my_folder after receiving the_files
tell application "Finder"
(* First create a new folder with name of folder = current date *)
set the_path to (folder "qa" of folder "Documents" of folder "ehmlab" of folder "Users" of disk "Macintosh HD")
set the_name to (item 1 of my myDate())
set the_name to (the_name & the_sep & item 2 of my myDate())
set the_name to (the_name & the_sep & item 3 of my myDate())
make folder at the_path with properties {name:the_name}
set newDir to the_path & the_name
end tell
(* Next, move the newly added files to the source into the newly created date folder *)
repeat with i from 1 to number of items in the_files
tell application "Finder"
try
set this_file to (item i of the_files)
move file this_file to folder newDir
end try
end tell
end repeat
do shell script "qc.sh " & newDir
end adding folder items to
on myDate()
set myYear to "" & year of (current date)
set myMth to text -2 thru -1 of ("0" & (month of (current date)) * 1)
set myDay to text -2 thru -1 of ("0" & day of (current date))
return {myYear, myMth, myDay}
end myDate
The failure reason are different path styles.
AppleScript uses HFS paths (colon separated).
UNIX uses POSIX paths (slash separated).
The solution is to coerce the HFS path string to POSIX path
do shell script "qc.sh " & quoted form of POSIX path of newDir
This is a shorter version of the script using the shell also for the time stamp and for creating the directory.
on adding folder items to my_folder after receiving the_files
(* Next, move the newly added files to the source into the newly created date folder,
"path to documents" is a relative path to the documents folder of the current user *)
set baseFolder to (path to documents folder as text) & "qa:"
set timeStamp to do shell script "date +%Y-%m-%d"
set newDir to baseFolder & timeStamp
do shell script "mkdir -p " & quoted form of POSIX path of newDir
(* Next, move the newly added files to the source into the newly created date folder *)
repeat with aFile in the_files
tell application "Finder"
try
move aFile to folder newDir
end try
end tell
end repeat
do shell script "qc.sh " & quoted form of POSIX path of newDir
end adding folder items to

Check file name for range of characters

Is there a way to tell Applescript to locate a file where the file name would match this type of criteria:
set foundFile to file whose name starts with
[character 0-9] followed by [character 0-9] followed by underscore
I can't think of a way to do it with a Finder whose clause statement. However grep has regular expression capabilities so try this...
set theFolder to choose folder
set foundFileNames to paragraphs of (do shell script "ls " & quoted form of POSIX path of theFolder & " | grep '^[0-9][0-9]_'")
set firstFoundFile to (theFolder as text) & item 1 of foundFileNames
Here's a handler that does this with all Applescript and no shell script.
-- get your folder however and feed the folder to the handler getMatchingFiles(*your folder*)
on getMatchingFiles(theFolder)
tell application "Finder"
set theFiles to every file of theFolder
set allDigits to "0123456789"
set matchingFiles to {}
repeat with aFile in theFiles
set fileName to the name of aFile
if ((the first character of fileName is in allDigits) and (the second character of fileName is in allDigits) and (the third character of fileName is "_")) then copy aFile to the end of matchingFiles
end repeat
end tell
return matchingFiles
end getMatchingFiles
regulus6633's answer is promising, but there's no need to resort to resort to external utilities ls and grep; the shell's own pathname expansion (globbing) is sufficient, using pattern [0-9][0-9]_*:
# Pick a folder.
set targetFolder to choose folder
# Get matching files.
# `shopt -s nullglob` instructs the shell to return an empty string, if no files match.
set foundFiles to paragraphs of (do shell script "shopt -s nullglob; printf '%s
' " & quoted form of POSIX path of targetFolder & "[0-9][0-9]_*")
# Extract the 1st matching file.
set foundFile to item 1 of foundFiles

(Automator/AppleScript) Rename files to a folder name, save to different folder & add prefix

I really need you help and will be very grateful for it.
I think this should be no problem for you.
So I have folder with different subfolders in it. In subfolders are images.
What I need is:
Change each image name to it’s subfolder name + 001 and so on («1stSubfolder001, 1stSubfolder002, …», «2ndSubfolder001, 2ndSubfolder002, …»)
Move all images from all subfolders to one folder (or at least to root folder)
Add random prefix number to names.
I have script to third task:
tell application "Finder"
repeat with this_item in (get items of window 1)
set name of this_item to ((random number from 0 to 99999) & name of this_item) as string
end repeat
end tell
But it only works with opened folder on the foreground. Maybe there is a way to make one script to run it on the background?
Huge thank you in advance.
I found cool automator app here, but I need to correct it a little bit.
How do I use the current folder name without a path as a variable in automator in Mac?
This script does everything I need BUT it renames all files to ONE folder name, not each different.
Here is another applescript that does rename files to folders, but it uses 2 folders name (folder + subfolder), and I need only subfolder prefix.
set myFolder to do shell script "sed 's/\\/$//' <<< " & quoted form of POSIX path of (choose folder)
set myFiles to paragraphs of (do shell script "find " & quoted form of myFolder & " \\! -name \".*\" -type f -maxdepth 2 -mindepth 2")
repeat with aFile in myFiles
tell application "System Events" to set file aFile's name to (do shell script "sed 's/.*\\/\\([^/]*\\)\\/\\([^/]*\\)\\/\\([^/]*$\\)/\\1_\\2_\\3/' <<< " & quoted form of aFile)
end repeat
(MacBook Pro Late 2013, OS X Yosemite 10.10.1)
This accomplishes what you want. You should be able to adjust from here. There are no checks to ignore non-image files.
property top_folder : alias "Macintosh HD:Users:MyName:Downloads:Images:"
property save_folder : ""
set save_folder to choose folder with prompt "Select the folder to save the images in."
process_folder(top_folder)
on process_folder(this_folder)
set these_items to list folder this_folder without invisibles
set container_name to name of (info for this_folder)
repeat with i from 1 to the count of these_items
set this_item to alias ((this_folder as Unicode text) & (item i of these_items))
if folder of (info for this_item) is true then
process_folder(this_item)
else
process_item(this_item, container_name, i)
end if
end repeat
end process_folder
-- this sub-routine processes files
on process_item(this_item, c, i)
-- make the integer a 3 digit string
if i < 10 then
set i to "00" & i
else if i < 100 then
set i to "0" & i
end if
-- set a random number
set r to (random number from 0 to 99999) as string
tell application "System Events"
-- get file extension so not overwritten
set e to name extension of this_item
set new_name to "" & r & "_" & c & "_" & i & "." & e
set name of this_item to new_name
move this_item to save_folder
end tell
end process_item

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

Resources