Delete part of a filename after specific charcters

Hi,

I’m looking for a applescript that deletes part of a file name after certain characters, for example:

N19-052-09_X_N20.pdf

I want it to delete everything after _X to get N19-052-09_X.pdf
The number of characters before and after the _X varies with the files i’m trying to rename.

I searched around and found some that where close to this, but don’t have enough experience to manipulate/understand the script to what I need.

Thank you!

There are a number of ways to do what you want. This is one:


set fileName to "N19-052-09_X_N20.pdf"
set splitCharacters to "_X"

set ATID to AppleScript's text item delimiters
set AppleScript's text item delimiters to splitCharacters
set newFileName to text item 1 of fileName & splitCharacters & ".pdf"
set AppleScript's text item delimiters to ATID

get newFileName # returns "N19-052-09_X.pdf"

This is another:


set fileName to "N19-052-09_X_N20.pdf"
set splitCharacters to "_X"

set splitOffset to (offset of splitCharacters in fileName) + (count splitCharacters) - 1
set newFileName to text 1 thru splitOffset of fileName & ".pdf"

get newFileName # returns N19-052-09_X.pdf

If some of the files to be renamed do not have a PDF extension, an additional step needs to be added to the above.

Hi Peavine,

Thank you for the help.

I forgot to mention that the number of characters and the characters themselves vary as well. The only constant would be the _X.

for example it could be:

N19-052-09_X_N20.pdf
N18-025_XA.pdf
N17-032-05_X_N17A.pdf

After the script it would be:

N19-052-09_X.pdf
N18-025_X.pdf
N17-032-05_X.pdf

I’m using Hazel and would like to make a folder where I drop these PDF’s in, and the embedded script runs to remove the characters after _X.

Thanks again.

ttokunaga. I’m pretty sure that both of my scripts work as you want. Just to demonstrate, I wrote the following script, which renames all PDF files with _X in their file name in a folder you select. I tested this on three files with the names you specify as examples and the script renamed these files as expected.


set stopCharacters to "_X"
set stopCharacterCount to (count stopCharacters)

set sourceFolder to choose folder default location (path to home folder)

tell application "Finder"
	set sourceFiles to (every file in sourceFolder ¬
		whose name contains stopCharacters and name ends with "pdf") as alias list
end tell

repeat with aFile in sourceFiles
	tell application "Finder" to set aFileName to name of aFile
	set stopOffset to (offset of stopCharacters in aFileName) + stopCharacterCount - 1
	set newFileName to text 1 thru stopOffset of aFileName & ".pdf"
	try
		tell application "Finder" to set name of aFile to newFileName
	on error errorMessage
		set dialogText to "The source file " & quote & aFileName & quote & ¬
			" could not be renamed. The error message was:" & return & return & errorMessage
		display dialog dialogText buttons {"Cancel", "Skip"} default button 1
	end try
end repeat

Hi Peavine,

the script works great!

I was wondering if there is a way to make it so I don’t get a prompt to choose the folder i want the script to run on.

I made a hot folder in Hazel where you can drop these pdfs in and it’s supposed to automatically run this script to rename these without having to choose a folder or hit play in the script editor.

Ideally I would like to just drop the files in and let the script do its job without any intervention.

Thank you very much for the help!

ttokunaga. You can avoid the choose-folder prompt by specifying a target folder in the script. To do this, delete the following line:

set sourceFolder to choose folder default location (path to home folder)

And, insert into its place the following (but with the desired folder path):

try
	set sourceFolder to alias "Macintosh HD:Users:peavine:myfolder:"
on error
	display dialog "The source folder could not be found." buttons {"OK"} ¬
		cancel button 1 default button 1
end try

I’m not familiar with Hazel and do not know what it requires in the form of an AppleScript or how it runs the AppleScript, so I can’t help with that.

Works amazing thanks!

The script works great after setting the folder location.

What if I had files in different folders within the same set location:

Main folder (where the script is directed to save)
Folder A
N19-052-09_X_N20.pdf
Folder B
N18-025_XA.pdf
Folder C
N17-032-05_X_N17A.pdf

Is there a way to leave out having to set a location and have it process all files within subfolders as well? At the moment it will only work with files within “main folder”

ttokunaga. It’s a bit difficult to do this without having the ability to test the script in Hazel, but I believe the following will do what you want. If many files are involved, the script could be slow.


set stopCharacters to "_X"
set stopCharacterCount to (count stopCharacters)

try
	set sourceFolder to alias "Macintosh HD:Users:peavine:myfolder:"
on error
	display dialog "The source folder could not be found." buttons {"OK"} ¬
		cancel button 1 default button 1
end try

tell application "Finder"
	set sourceFiles to ((files of entire contents of sourceFolder) ¬
		whose name contains stopCharacters and name ends with "pdf") as alias list
end tell

repeat with aFile in sourceFiles
	tell application "Finder" to set aFileName to name of aFile
	set stopOffset to (offset of stopCharacters in aFileName) + stopCharacterCount - 1
	set newFileName to text 1 thru stopOffset of aFileName & ".pdf"
	try
		tell application "Finder" to set name of aFile to newFileName
	on error errorMessage
		set dialogText to "The source file " & quote & aFileName & quote & ¬
			" could not be renamed. The error message was:" & return & return & errorMessage
		display dialog dialogText buttons {"Cancel", "Skip"} default button 1
	end try
end repeat

This works!

Thank you very much, you are a life saver!

I tried an alternate scheme.

(1) Create a droplet which may do the job two ways,
(a) running the script offer the choose folder dialog
(b) dropping a folder onto the icon of the script saved as an application


on run
	set sourceFolder to choose folder default location (path to home folder)
	Germaine(sourceFolder)
end run

on open sel
	tell application "Finder"
		set theClass to class of (get properties of (item 1 of sel))
		if theClass is folder then
			my Germaine(item 1 of sel)
		end if
	end tell
end open


on Germaine(sourceFolder)
	set stopCharacters to "_X"
	set stopCharacterCount to (count stopCharacters)
	tell application "Finder"
		set sourceFiles to (every file in sourceFolder ¬
			whose name contains stopCharacters and name ends with "pdf") as alias list
	end tell
	
	repeat with aFile in sourceFiles
		tell application "Finder" to set aFileName to name of aFile
		set stopOffset to (offset of stopCharacters in aFileName) + stopCharacterCount - 1
		set newFileName to text 1 thru stopOffset of aFileName & ".pdf"
		tell application "Finder"
			try
				set name of aFile to newFileName
			on error errorMessage
				set dialogText to "The source file " & quote & aFileName & quote & ¬
					" could not be renamed. The error message was:" & return & return & errorMessage
				display dialog dialogText buttons {"Cancel", "Skip"} default button 1
			end try
		end tell
	end repeat
end Germaine

(2) Attach the script below, saved as a script in your folder actions scripts folder:
“/Users/**********/Library/Scripts/Folder Action Scripts/”

on adding folder items to this_folder after receiving these_items
	-- CHECK FOR THE DESTINATION FOLDER WITHIN THE ATTACHED FOLDER
	-- IF IT DOESN'T EXIST, THEN CREATE IT
	set sourceFolder to (item 1 of these_items)
	
	
	set stopCharacters to "_X"
	set stopCharacterCount to (count stopCharacters)
	tell application "Finder"
		set sourceFiles to (every file in sourceFolder ¬
			whose name contains stopCharacters and name ends with "pdf") as alias list
	end tell
	
	repeat with aFile in sourceFiles
		tell application "Finder" to set aFileName to name of aFile
		set stopOffset to (offset of stopCharacters in aFileName) + stopCharacterCount - 1
		set newFileName to text 1 thru stopOffset of aFileName & ".pdf"
		tell application "Finder"
			try
				set name of aFile to newFileName
			on error errorMessage
				set dialogText to "The source file " & quote & aFileName & quote & ¬
					" could not be renamed. The error message was:" & return & return & errorMessage
				display dialog dialogText buttons {"Cancel", "Skip"} default button 1
			end try
		end tell
	end repeat
	
end adding folder items to

Attaching is a bit cumbersome because we need to use the application:
“/System/Library/CoreServices/Applications/Folder Actions Setup.app/”

To get an easier access, I created a symbolic link pointing upon this app on the Desktop.

Yvan KOENIG running High Sierra 10.13.6 in French (VALLAURIS, France) lundi 19 aout 2019 21:26:58

Yvan. Thanks for posting the folder actions script. I never really understood how they worked but with a good example everything became clear. I’ve never much cared for droplets , which I found cumbersome to use, but folder actions scripts are much more flexible and easy to use.

Probably the hardest part is getting access to the setup app. I ended up making a one-line AppleScript to start it.

Thank you Peavine

At first I wrote a code supposed to gather the three protocols in a single one but when it was finished I remember that folder actions must be saved as scripts, not as applications.

With the asked question, the answer was simple because we are supposed to drop a folder into the hot folder (the one to which the script is attached).
When we have to treat dropped files, we must remember what is written in the guide:
[format]A well written Folder Action script leaves the hot folder empty. This avoids repeated application of the action to the same files, and allows Folder Actions to perform more efficiently.[/format]

Yvan KOENIG running High Sierra 10.13.6 in French (VALLAURIS, France) mardi 20 aout 2019 09:22:43

As an exercise I built this multipurpose folder actions script :

--set this_folder to ((path to desktop as text)&"hotFolder:") as alias
--set these_items to ((path to desktop as text)&"19932.jpg") as alias}

on adding folder items to this_folder after receiving these_items
	-- CHECK FOR THE DESTINATION FOLDER WITHIN THE ATTACHED FOLDER
	-- IF IT DOESN'T EXIST, THEN CREATE IT
	
	repeat with anItem in these_items # these_items is a list of aliases
		set itsInfos to info for anItem
		set {isFolder, isPackage} to {folder, package folder} of itsInfos
		if isFolder and (not isPackage) then
			set itsID to "folder" # fake type identifier
		else
			set itsID to type identifier of itsInfos
		end if
		-- some samples
		-- {true, false, "folder"} for a folder
		-- {false, false, "com.apple.applescript.script"}
		-- {false, false, "com.adobe.pdf"}
		-- {false, false, "public.jpeg"}
		-- {false, false, "public.png"}
		-- {false, false, "public.tiff"}
		-- {false, false, "com.apple.iwork.pages.sffpages"}
		-- {false, false, "com.apple.iwork.pages.pages"}
		-- {false, false, "com.apple.iwork.numbers.sffnumbers"}
		-- {true, true, "com.apple.iwork.numbers.numbers"}
		-- {true, true, "com.apple.rtfd"}
		-- {true, true, "com.apple.application-bundle"
		
		if itsID = "folder" then
			my treatThisFolder(anItem, this_folder)
		else if itsID is "com.adobe.pdf" then
			my treatPDF(anItem, this_folder)
		else if itsID starts with "com.apple.iwork" then
			my treatIworkDoc(anItem, this_folder, itsID)
		else if itsID is in {"public.jpeg", "public.png", "public.tiff"} then # you may add other IDs
			my treatPicture(anItem, this_folder, itsID)
		else if itsID is "?!?!" then
			--
		end if
	end repeat
	
end adding folder items to

on treatThisFolder(sourceFolder, this_folder)
	set stopCharacters to "_X"
	set stopCharacterCount to (count stopCharacters)
	tell application "Finder"
		set sourceFiles to (every file in sourceFolder ¬
			whose name contains stopCharacters and name ends with "pdf") as alias list
	end tell
	
	repeat with aFile in sourceFiles
		tell application "Finder" to set aFileName to name of aFile
		set stopOffset to (offset of stopCharacters in aFileName) + stopCharacterCount - 1
		set newFileName to text 1 thru stopOffset of aFileName & ".pdf"
		tell application "Finder"
			try
				set name of aFile to newFileName
			on error errorMessage
				set dialogText to "The source file " & quote & aFileName & quote & ¬
					" could not be renamed. The error message was:" & return & return & errorMessage
				display dialog dialogText buttons {"Cancel", "Skip"} default button 1
			end try
		end tell
	end repeat
end treatThisFolder

on treatPDF(anItem, this_folder)
	set targetFolder to my buildFolder(this_folder, "treated PDFs")
	# now we may move the PDF in to targetFolder and treat the moved file
end treatPDF

on treatIworkDoc(anItem, this_folder, itsID)
	set targetFolder to my buildFolder(this_folder, "treated iWork docs")
	# itsID allow us to select the correct tratment to apply
	# now we may move the iWork doc in to targetFolder and treat the moved file
end treatIworkDoc

on treatPicture(anItem, this_folder, itsID)
	set targetFolder to my buildFolder(this_folder, "treated Pictures")
	# itsID allow us to select the correct tratment to apply
	# now we may move the picture file in to targetFolder and treat the moved file
end treatPicture

on buildFolder(this_folder, folderName)
	set destinationFolder to (this_folder as text) & folderName & ":"
	tell application "Finder"
		if not (exists folder destinationFolder) then
			make new folder at this_folder with properties {name:folderName}
		end if
	end tell
	return destinationFolder as alias
end buildFolder

The two first instructions (enabled) are used to test the script after disabling the instructions:

[format]on adding folder items to this_folder after receiving these_items
end adding folder items to[/format]

Yvan KOENIG running High Sierra 10.13.6 in French (VALLAURIS, France) mardi 20 aout 2019 11:21:18

Folder Actions Setup itself is scriptable. It’s dictionary doesn’t make it obvious how to do things, but I believe you can – or at least used to be able to – set folder actions up via script.

You’re right Shane but double clicking upon an icon is my preferred protocol.

I never understood why Folder Actions Setup.app which was stored as “/Applications/Applescript/Folder Actions Setup.app/” was ‘hidden’ into “/System/Library/CoreServices/Applications/Folder Actions Setup.app/”

Yvan KOENIG running High Sierra 10.13.6 in French (VALLAURIS, France) mardi 20 aout 2019 16:16:34