A Script to Find and Replace Layer Names
Are there any scripts to find and replace layer names?
There is an excellent script available for Photoshop which allows you to not only replace words in layer names, but also insert words as Prefixes, Suffixes and Sequential Numbers.
The illustrator version of this script only allows sequential numbering: It doesn't offer find and replacing of words.
Ideally, it would be great if there was something that could do multiple find and replaces in one go:
(e.g.
You have layers like this Car, Dog, Bat
You enter: car(Option1), dog(Option2), Bat(Option3)
Your layers then become: Option1, Option2, Option3).
big_smile, that's a very good start! Step 1 of Learning How To Script is indeed, adjusting an existing simple script to make it do more complicated things. (And usually then "break something", which is also a required part of the process.)
You are correct in your observation this is repetitive stuff. For one or two different items that wouldn't be a problem, but in longer lists you soon get lost.
The usual way of working with find-change lists is to build an array:
var layernames = [
[ 'FHairBowlBoy *Hair', 'Hairboy1' ],
[ 'FHairCurlyafroBoy *Hair', 'Hairboy2' ],
[ 'FHairSpikyBoy *Hair', 'Hairboy3' ],
The general idea is to loop over all names, check if the current layer name is "layernames[i][0]" (the left column) and if so, rename it to "layernames[i][1]" (the right column). If you know how to write a loop in Javascript, then you can implement this right away.
However ..
A more advanced way to do this doesn't even need loop to over all layernames -- instead you can immediately "get" the correct name per layer! It's magic! Almost!
The trick is to use a Javascript object instead of an array. Javascript objects are nothing special; Illustrator's 'layers' is an array of objects, and each object "layer" has a property "name", whose value you can read and set. What I do here is create a new object, where the "name" part is the original layer name and its value is the new layer name. All you need to check for per each layer is if there is a property 'object.originalLayerName', and if so, assign its value to that layer name.
This looks a bit like the array above, except that (1) you use {..} instead of [..] to create an object, and (2) you add "name:value" pairs instead of "value" only (actually, the 'name' of a value in an array is simply its number).
So this is what it looks like:
// JavaScript Document
var doc = app.activeDocument;
// name indexed object
var layernames = {
'FHairBowlBoy *Hair':'Hairboy1',
'FHairCurlyafroBoy *Hair':'Hairboy2',
'FHairSpikyBoy *Hair':'Hairboy3'
// loop through all layers
for (var i = 0; i < doc.layers.length; i++)
//Set up Variable to access layer name
var currentLayer = app.activeDocument.layers[i];
if (layernames[currentLayer.name])
currentLayer.name = layernames[currentLayer.name];
Enjoy!
Similar Messages
-
Is there a script to find and replace glyphs?
I am using Adobe Illustrator CC 2014, Build 10.1.0.70.
I am looking for a way to quickly find and change certain glyphs within a typeface much like InDesign's Find/Change feature with a script that runs through saved queries. Is this at all possible..?Hi Steve, thanks for your quick response.
My apologies I should've made myself clearer... I was more thinking about a script to run a chain of preset saved find and replace queries together. I have 48 individual glyphs from one typeface that I need to consistently apply across whole ducunents. Rather than click through each glyph for every single document I come across I was hoping there was a way to automate the process.
Thanks -
Dear all, I have a few eps files in which month-year format is written like May-12, June-13 etc. I want to change May to Mai, June to Juin etc.
Virender
var myDoc = app.activeDocument;
for (i = 0; i < myDoc.textFrames.length; i++ )
var textArt = myDoc.textFrames[i];
for (j =0; j < textArt.words.length; j++ )
var word = textArt.words[j];
switch (word.contents)
case "May-\d\d": // please advise here
word.contents = "Mai";
break;
case "Mar-\d\d":
word.contents = "Mrz";
break;
case "June-\d\d":
word.contents = "Juin";
break;
alert("Done");Vielen Dank pixxxel schubser.
I worte below script as per your suggustion and my requirements. Meanwhile this scipt convert English month to german months. Any possibility I can create a script which ask me for German, French and Italy buttons. So if I click on German button, then German's month coding execute and if i click on French then French's month coding execute and so on. I knew it can be done using dialog (in Indesign I sure) but not sure in Illustrator. Kindly advise.
var myDoc = app.activeDocument;
for (i = 0; i < myDoc.textFrames.length; i++ )
var textArt = myDoc.textFrames[i];
for (j =0; j < textArt.words.length; j++ )
var word = textArt.words[j];
word.contents = word.contents.replace ("Mar", "Maz");
word.contents = word.contents.replace ("May", "Mai");
word.contents = word.contents.replace ("Oct", "Okt");
word.contents = word.contents.replace ("Dec", "Dez");
//alert("Done"); -
Indesign script to find and replace from external excel file
I have been asked to update an existing price list (set up as lots of small tables) in Indesign (500+ pages). I have been given a new Excel spreadsheet with the product codes and new prices. I am looking for some assistance on finding or creating a script that can do such a thing if at all possible to speed up the process over just copying and pasting. Does anyone have any suggestions or point me in the right direction?
1. Your Excel conversion to FindChangeList format idea seems okay, apart from one thing: both findWhat and changeTo strings should have double quotes around them. As they are now,
grep {findWhat:lang1"} {changeTo:"lang2} {incl...(etc.)
the opening one after findWhat and the closing one after changeTo are missing.
2. Your first line contains 2 definitions. Each separate definition should be on a line of its own. (This might occur elsewhere as well, didn't check.)
3. Any double quotes inside strings will cause problems. Precede them with a backslash to 'escape' them and convert them to a literal character. I found this one:
"(for IC5/8"V)"
-- change to
"(for IC5/8\"V)"
4. Some of your strings start with double double quotes:
changeTo:""(MITM刀具见254页 ...
5. To prevent your problem with this order
grep {findWhat:Inserts"} ...
grep {findWhat:Inserts Ordering Code System"} ...
sort your Excel list alphabetically, case preserving, in reverse order.
You probably also want wholeWord:true, and caseSensitive:true.
Hope this helps! -
Replace layer names in selected layers only
I am using this script to find and replace words in layers. (The script only targets particualr words, rather than the whole layer name).
I would like to make it so it targets selected layers only.
I have found this script which loops through selected layers only, but I am not sure how to add the find and replace layer name functioality.
Thanks for any help that can be offered.big_smile wrote:
Looking through the guide, it doesn't seem "hasSelectedArtwork", is a built in function either. Are there any tutorials or guides that explain how to target selected layers?
Wrong reference manual, see this one:
http://www.adobe.com/content/dam/Adobe/en/devnet/pdf/illustrator/scripting/cs6/Illustrator -Scripting-Reference-JavaScript.pdf
Page 91 -- CHAPTER 1: JavaScript Object Reference
Layer
Property
hasSelectedArtwork
Value type
boolean
What it is
If true, an object in this layer has been selected; set to false to deselect all objects in the layer.
So as I talked about here:
W_J_T wrote:
Correct. Yeah there is no direct way unfortunately (like many things via scripting), thats why I suggested using "hasSelectedArtwork", that would work if you select the layer target when selecting your desired layers to rename.
and...
W_J_T wrote:
if(layerReferenceString.hasSelectedArtwork == true){
// relative code
That would offer a way to know if a layer is selected or not.
As far as I know that is the only round about way of knowing if a layer is selected via scripting. -
Rename Layers: Find and Replace style renaming
In Illustrator, you can use the following to find and replace layer names:
var doc = app.activeDocument;
// name indexed object
var layernames = {
'Bob':'Bob Front'
// loop through all layers
for (var i = 0; i < doc.layers.length; i++)
//Set up Variable to access layer name
var currentLayer = app.activeDocument.layers[i];
if (layernames[currentLayer.name])
currentLayer.name = layernames[currentLayer.name];
In this script "Bob" will become "Bob Front". Is there something similar for Photoshop. Looking at the Photoshop scripting guide, this script should work as the active App document and layers methods exist in Photoshop.c.pfaffenbichler wrote:
What are
var layernames = {
'Bob':'Bob Front'
and
if (layernames[currentLayer.name])
supposed to do? Is that even JavaScript? …
Hi c.pfaffenbichler, yes, this is pure Javascript.
Try this little example:
var layernames = {'Bob':'Bob Behind'};
alert(layernames['Bob']);
// a variant
layernames['Bob'] = 'Bob in the middle';
alert("a variant: " + layernames['Bob']);
// another variant
layernames.Bob = 'Bob Front';
alert("another variant: " + layernames.Bob);
@big_smile,
your posted script works with photoshop (if you have only artlayers and one or more layers named with Bob)
var doc = app.activeDocument;
// name indexed object
var layernames = {'Bob':'Bob Front'};
// loop through all layers
for (var i = 0; i < doc.layers.length; i++) {
//Set up Variable to access layer name
var currentLayer = app.activeDocument.layers[i];
if (layernames[currentLayer.name]) {
currentLayer.name = layernames[currentLayer.name];
All you have to do is to loop trough all artlayers (and layersets), but here is Javascript a slowly variant. Use ActionManager code instead. You will find many examples here in forum.
Have fun -
I have to do complicated reformatting of an entire site. It's been simplified to a series of find and replace tasks for each file. Each find and replace string has been saved as a .dwr file. Currently I have to load and execute each .dwr file.
How do you batch process or automate this task in Dreamweaver? In other words, queue up a series of .dwr files to be executed consecutively?OK here we go.
This example, a simple Dreamweaver Command Extension, will execute two Find and Replace commands in one go. (It can be any number of Find and Replace commands.)
The first command replaces "the" and "this" with "phe" and "phis". The second command replaces <ul> ... </ul> with <ol> ... </ol>. (These of course can be any Find and Replace.)
You need two files: a HTML file (for the UI) and a Javascript file (for actions). I named them "Find and Replace Test.html" and "Find and Replace Test.js". (They can be any name.)
Find and Replace Test.html
<!DOCTYPE HTML SYSTEM "-//Adobe//DWExtension layout-engine 10.0//dialog">
<HTML>
<HEAD>
<Title>Find and Replace Test</Title>
<script src="Find and Replace Test.js"></script>
</HEAD>
<BODY>
<form>
<p>Are you sure?</p>
</form>
</BODY>
</HTML>
Find and Replace Test.js
function canAcceptCommand() {
return true;
function commandButtons() {
return new Array("Go!", "doIt()", "Cancel", "window.close()");
function doIt() {
dreamweaver.setUpFindReplace({
searchString: "th(e|is)",
replaceString: "ph$1",
searchWhat: "document",
searchSource: true,
useRegularExpressions: true
dreamweaver.replaceAll();
dreamweaver.setUpFindReplace({
searchString: "<(/?)ul>",
replaceString: "<$1ol>",
searchWhat: "document",
searchSource: true,
useRegularExpressions: true
dreamweaver.replaceAll();
window.close();
Basically you can call any number of this pair of functions in the script:
dreamweaver.setUpFindReplace(findAndReplaceObject);
dreamweaver.replaceAll();
Place these HTML and JS files in this directory:
Dreamweaver App Directory/Configuration/Commands/
Then in Dreamweaver, open "Insert" window. (You need to have a HTML file open in order to make the Insert window active.) At the top of the Insert window there's a category dropdown menu ("Common" etc.). Do alt + click (ctrl + click) - then you'll see an item "Reload Extenesions" at the bottom of the dropdown. This will load this extension to DW. (Alternatively you can restart DW to load the extension.)
Now it's ready to run the Extension. Open a HTML document you want to modify. Go to "Commands" on the menu bar. At the bottom of the dropdown there should be an item "Find and Replace Test". Select and enjoy
Notes
This example is set to perform the Find and Replace on the current document. You can change the scope to the entire site, or the selected files, etc, just like in the Find and Replace dialogue box. The API doc is here: http://help.adobe.com/en_US/dreamweaver/cs/apiref/WS5b3ccc516d4fbf351e63e3d117f9e09bcf-7ed a.html
You can use dreamweaver.setUpComplexFindReplace(xmlQueryString) command instead. xmlQueryString is basically <dwquery> ... </dwquery> in your .dwr files, you can copy from your .dwr files. However xmlQueryString needs to be one continuous string (no line breaks), which can be a pain The doc: http://help.adobe.com/en_US/dreamweaver/cs/apiref/WS5b3ccc516d4fbf351e63e3d117f9e09bcf-7ed 9.html
Command Extension general example in the doc: http://help.adobe.com/en_US/dreamweaver/cs/extend/WS5b3ccc516d4fbf351e63e3d117f53d6ec3-7fe 6.html
I hope all of these make sense...
Kenneth Kawamoto
http://www.materiaprima.co.uk/ -
"Find and Replace" for field names in a fillable PDF
Is it possible to do a "Find and Replace" for the field names in a fillable PDF? For example, I have multiple fields that contain the word "Proposed Insured" as part of the field name and would like to find and replace all of them with "Owner". Is there an easy way to do this?
Not really. Even a script can't just rename a field. It needs to create a
new field on top of the old one, but then you lose all the associated
settings, like validation, calculation, format, keystroke, etc. -
Find and replace characters in file names
I need to transfer much of my user folder (home) to a non-mac computer. My problem is that I have become too used to the generous file name allowances on the Mac. Many of my files have characters such as "*" "!" "?" and "|". I know these are problems because they are often wild cards (except the pipe). Is there a way that I can do a find and replace for these characters?
For example, search for all files with an "*" and replace the "*" in the file name with an "@" or a letter? I don't mind having to use the terminal for this (I suspect it will be easier).
Is this possible? Does anyone have any suggestions?
Thank you in advance for any help you may be able to provide.
Mac OS X (10.4.8)Yep.
"A Better Finder Rename" is great for batch file renaming.
http://www.versiontracker.com/dyn/moreinfo/macosx/11366
Renamer4mac may be all you need.
Best check out VersionTracker. In fact everybody should have this site bookmarked and visited daily.
http://www.versiontracker.com/macosx/ -
Script to find files with same names with in a folder and it sub folders.
Looking for script to find files with same names with in a folder and it sub folders.
Are you just looking to find if any two files underneath a folder have the same name?
If you just want to know that a file named "whatever" exists in two folders, that's not too difficult, but you probably want to know the full path names.
Here's one attempt:
$ perl -MFile::Find -le 'find(\&w, "."); while (($n,$p)=each %file) {if(@{$p}>1){print join(" ",@{$p})}} sub w{push @{$file{$_}},$File::Find::name;}'That will print the pathnames on the same line of any files with the same name that appear anywhere underneath your current directory.
It's a bit long for a "one-liner", but functional.
Darren -
Do there is any way to redefine styles by find and replace or script
I have a some styles and i want to change same things in all styles like language, align and numbers digit and etc....,
So I ask if there is an easy way to do that except modify each style manual, like script?, I use inDesgin CS3, and CS4
Like in Find Font there is option to redefine styles but that for fonts only, So there is way to do that by find and replace ?
ThanksI'm not a "scripter" and I don't have a huge knowledge of what scripts are available, unlike some on here, but this is how I'd do it if I couldn't find what I wanted by googling.
-
Using applescript for Find and Replace All in Pages 2.0
i saw that Pages 2.0 is scriptable
i try to create a script for merge use to find and replace all occurence of a certain string using a script but Pages doesn't seems to respond to "Find" even using "System Events"
how can i do to use this function with a script
Thanx for any help
S.B.
ibook G3 Mac OS X (10.4.6)OK, here's another example. This one gets the text as a string and uses the offset property to find "[", presuming it to be a merge delimiter. (Pages' text doesn't support "offset of").
One failing of this scheme is that the offsets are incorrect if you have inline objects (pictures, shapes, tables, etc.). While it is probably possible to compensate for them, that's a trickier proposition.
<PRE>-- Example merge replacements:
property mergeText : {"[name]", "John Smith", "[address]", "1234 Anystreet"}
on lookup(mergeWord)
set theCount to count of mergeText
repeat with x from 1 to theCount by 2
if item x of mergeText = mergeWord then
return item (x + 1) of mergeText
end if
end repeat
-- If merge field is not found, delete it (replace it with the empty string)
return ""
end lookup
tell application "Pages"
repeat
tell body text of document 1
-- Get text as a string so that "offset of" can be used.
set allText to it as string
set startOffset to offset of "[" in allText
if (startOffset = 0) then
exit repeat
end if
set endOffset to offset of "]" in allText
select (text from character startOffset to character endOffset)
end tell
set mergeWord to contents of selection
tell me to lookup(mergeWord)
set replacement to result
set selection to replacement
if (replacement is "") then
-- Get rid of extra whitespace (space or return)
-- Do it in a "try" block to handle edge cases at start or end of text.
try
set theSel to (get selection)
set ch1 to character before theSel
set ch2 to character after theSel
if ((ch1 is " " or ch1 is return) and (ch2 is " " or ch2 is return)) then
select character after theSel
delete selection
end if
end try
end if
end repeat
end tell</PRE>
Titanium PowerBook Mac OS X (10.4.6) -
Find and replace with multiple files and with a watch folder
I am trying to create a watch folder that uses red_menace script to:
1. Have a folder that receives multiple xml files that run the script one by one.
2. then move the files to an output folder.
I tried modifying the set TheFIle to choose file -- the original text file to:
with multiple selections allowed
But that doesn't seem to work. I know i'm missing a step. Any help is much appreciated!
Thanks!
The way i'd like to setup things is having an input folder on the desktop (or just have the application on the desktop and I can drag the files onto it), and let it do it's thing. Once it's done have it export the xml files into an output folder.
Here's what i got so far:
on open
set TheFIle to choose file -- the original text file
set TheFolder to ("Macintosh HD:Users:user1:Desktop:out") -- the folder for the output file
set TheName to (GetUniqueName for TheFIle from TheFolder) -- the name for the output file
set TheText to read TheFIle -- get the text to edit
set Originals to {"KPCALDATE", "KPCALEVENT", "KPCALDAY", "KPCALBODY", "obituaries name", "" & return & "</cstyle></pstyle>" & return & "<pstyle name=\"obituaries text\"><cstyle>", "<pstyle name=\"obituaries text\"><cstyle name=\"Graphics Bold leadin\" font=\"ADV AGBook-Medium 2\">", "<pstyle name=\"Recipe Ingredients\"><cstyle>", " .com", " .net", " .org", " .edu", "www .", "www. ", "Ho- nolulu", "<pstyle name=\"kicker 12\"><cstyle allcaps=\"1\">fashion news</cstyle><cstyle allcaps=\"1\">" & return & "</cstyle></pstyle>" & return & "", "<component name=\"Headline 1\" type=\"Headline\">" & return & "<header>" & return & "<field name=\"Component name\" type=\"string\" value=\"Headline 1\"/>" & return & "<field name=\"Component type\" type=\"popup\" value=\"Headline\"/>" & return & "</header>" & return & "<body>" & return & "<pstyle name=\"hed STANDARD 36\"><cstyle>", "<pstyle name=\"obituaries text\"><cstyle allcaps=\"1\">", "<pstyle name=\"obituaries text\"><cstyle name=\"Graphics Bold leadin\">", "<pstyle name=\"tagline\"><cstyle>-", "-", "
Per serving:", "<pstyle name=\"Titlebar - mini, red\"><cstyle allcaps=\"1\">NATION & World </cstyle><cstyle allcaps=\"1\">Report</cstyle><cstyle allcaps=\"1\">" & return & "</cstyle></pstyle>" & return & "", "</cstyle></pstyle>"} -- the terms that can be replaced
set Replacements to {"subhed", "subhed", "subhed", "Normal", "obituaries text", ", ", "<pstyle name=\"obituaries text\"><cstyle name=\"Graphics Bold leadin\" font=\"ADV AGBook-Medium 2\">", "<pstyle name=\"Recipe Ingredients\"><cstyle>
", ".com", ".net", ".org", ".edu", "www.", "www.", "Honolulu", "", "<component name=\"Headline1\" type=\"Headline\">" & return & "<header>" & return & "<field name=\"Component name\" type=\"string\" value=\"Headline1\"/>" & return & "<field name=\"Component type\" type=\"popup\" value=\"Headline\"/>" & return & "</header>" & return & "<body>" & return & "<pstyle name=\"hed STANDARD 27\"><cstyle>", "<pstyle name=\"obituaries text\"><cstyle allcaps=\"1\">", "<pstyle name=\"obituaries text\"><cstyle name=\"Graphics Bold leadin\">", "<pstyle name=\"tagline\"><cstyle>", " ", "
Per serving:", "","" & return & "</cstyle></pstyle>"} -- the replacement terms
repeat with AnItem from 1 to count Originals
set TheText to (replaceText of TheText from (item AnItem of Originals) to (item AnItem of Replacements))
end repeat
try -- write a new output file
tell application "Finder" to make new file at TheFolder with properties {name:TheName}
set OpenFile to open for access (result as alias) with write permission
write TheText to OpenFile starting at eof
close access OpenFile
on error errmess
try
log errmess
close access OpenFile
end try
end try
end open
to GetUniqueName for SomeFile from SomeFolder
check if SomeFile exists in SomeFolder, creating a new unique name if needed
parameters - SomeFile [mixed]: a source file path
SomeFolder [mixed]: a folder to check
returns [text]: a unique file name and extension
set {Counter, Divider} to {"00", "_"}
-- get the name and extension
set {name:TheName, name extension:TheExtension} to info for file (SomeFile as text)
if TheExtension is missing value then set TheExtension to ""
set TheName to text 1 thru -((count TheExtension) + 2) of TheName
set NewName to TheName & "." & TheExtension
tell application "System Events" to tell (get name of files of folder (SomeFolder as text))
repeat while it contains NewName
set Counter to text 2 thru -1 of ((100 + Counter + 1) as text) -- leading zero
set NewName to TheName & Divider & Counter & "." & TheExtension
end repeat
end tell
return NewName
end GetUniqueName
to EditItems of SomeItems given Title:TheTitle, Prompt:ThePrompt
displays a dialog for multiple item edit (note that a return is used between each edit item)
for each of the items in SomeItems, a line containing it's text is placed in the edit box
the number of items returned are padded or truncated to match the number of items in SomeItems
parameters - SomeItems [list]: a list of text items to edit
TheTitle [boolean/text]: use a default or the given dialog title
ThePrompt [boolean/text]: use a default or the given prompt text
returns [list]: a list of the edited items, or {} if error
set {TheItems, TheInput, TheCount} to {{}, {}, (count SomeItems)}
if TheCount is less than 1 then return {} -- error
if ThePrompt is in {true, false} then -- "with" or "without" Prompt
if ThePrompt then
set ThePrompt to "Edit the following items:" & return -- default
else
set ThePrompt to ""
end if
else -- fix up the given prompt a little
set ThePrompt to ThePrompt & return
end if
if TheTitle is in {true, false} then if TheTitle then -- "with" or "without" Title
set TheTitle to "Multiple Edit Dialog" -- default
else
set TheTitle to ""
end if
set {TempTID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, return}
set {SomeItems, AppleScript's text item delimiters} to {SomeItems as text, TempTID}
set TheInput to paragraphs of text returned of (display dialog ThePrompt with title TheTitle default answer SomeItems)
repeat with AnItem from 1 to TheCount -- pad/truncate entered items
try
set the end of TheItems to (item AnItem of TheInput)
on error
set the end of TheItems to ""
end try
end repeat
return TheItems
end EditItems
to replaceText of SomeText from OldItem to NewItem
replace all occurances of OldItem with NewItem
parameters - SomeText [text]: the text containing the item(s) to change
OldItem [text]: the item to be replaced
NewItem [text]: the item to replace with
returns [text]: the text with the item(s) replaced
set SomeText to SomeText as Unicode text -- TID's are case insensitive with Unicode text
set {TempTID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, OldItem}
set {ItemList, AppleScript's text item delimiters} to {text items of SomeText, NewItem}
set {SomeText, AppleScript's text item delimiters} to {ItemList as text, TempTID}
return SomeText
end replaceText
Message was edited by: gamebreakersWhen you use the open or adding folder items to handlers, you need to add the parameters for the file items passed to them.
I'll go ahead and post the applet/droplet version of my original script from the previous topic for reference:
<pre style="
font-family: Monaco, 'Courier New', Courier, monospace;
font-size: 10px;
margin: 0px;
padding: 5px;
border: 1px solid #000000;
width: 720px; height: 340px;
color: #000000;
background-color: #FFEE80;
overflow: auto;"
title="this text can be pasted into the Script Editor">
-- search and replace multiple items applet/droplet/folder action
-- the terms to replace - edit as needed
property EditableItems : {¬
"one", ¬
"two", ¬
"three", ¬
"four", ¬
"five", ¬
"six", ¬
"seven", ¬
"eight", ¬
"nine", ¬
"ten", ¬
"eleven", ¬
"twelve", ¬
"thirteen", ¬
"fourteen", ¬
"fifteen", ¬
"sixteen", ¬
"seventeen", ¬
"eighteen", ¬
"nineteen", ¬
"twenty"}
-- the folder for the output file(s) - change as needed
property TheFolder : (path to desktop)
property LastEditItems : EditableItems
on run
the applet/droplet was double-clicked
open (choose file with multiple selections allowed)
end run
on open TheItems
items were dropped onto the applet/droplet
parameters - TheItems [list]: a list of the items (aliases) dropped
returns nothing
repeat with AnItem in TheItems
ReplaceMultipleItems from AnItem
end repeat
end open
on adding folder items to this_folder after receiving these_items
folder action - items were added to a folder
parameters - this_folder [alias]: the folder added to
these_items [list]: a list if items (aliases) added
returns nothing
repeat with AnItem in these_items
ReplaceMultipleItems from AnItem
end repeat
end adding folder items to
to ReplaceMultipleItems from SomeFile
replace multiple text items in SomeFile
parameters - SomeFile [alias]: the file to replace items in
returns nothing
set TheName to (GetUniqueName for SomeFile from TheFolder) -- the name for the output file
set TheText to read SomeFile -- get the text to edit
set Originals to (choose from list EditableItems default items LastEditItems with prompt "Select the terms to replace:" with multiple selections allowed) -- the specific terms to replace
set LastEditItems to Originals
set Replacements to (EditItems of Originals with Title given Prompt:"Edit the following replacement terms:") -- the replacement terms
repeat with AnItem from 1 to count Originals
set TheText to (ReplaceText of TheText from (item AnItem of Originals) to (item AnItem of Replacements))
end repeat
try -- write a new output file
tell application "Finder" to make new file at TheFolder with properties {name:TheName}
set OpenFile to open for access (result as alias) with write permission
write TheText to OpenFile starting at eof
close access OpenFile
on error errmess
try
log errmess
close access OpenFile
end try
end try
end ReplaceMultipleItems
to GetUniqueName for SomeFile from SomeFolder
check if SomeFile exists in SomeFolder, creating a new unique name if needed
parameters - SomeFile [mixed]: a source file path
SomeFolder [mixed]: a folder to check
returns [text]: a unique file name and extension
set {Counter, Divider} to {"00", "_"}
-- get the name and extension
set {name:TheName, name extension:TheExtension} to info for file (SomeFile as text)
if TheExtension is in {missing value, ""} then
set TheExtension to ""
else
set TheExtension to "." & TheExtension
end if
set {NewName, TheExtension} to {TheName, (ChangeCase of TheExtension to "upper")}
set TheName to text 1 thru -((count TheExtension) + 1) of TheName
tell application "System Events" to tell (get name of files of folder (SomeFolder as text))
repeat while it contains NewName
set Counter to text 2 thru -1 of ((100 + Counter + 1) as text) -- leading zero
set NewName to TheName & Divider & Counter & TheExtension
end repeat
end tell
return NewName
end GetUniqueName
to EditItems of SomeItems given Title:TheTitle, Prompt:ThePrompt
displays a dialog for multiple item edit (note that a return is used between each edit item)
for each of the items in SomeItems, a line containing it's text is placed in the edit box
the number of items returned are padded or truncated to match the number of items in SomeItems
parameters - SomeItems [list]: a list of text items to edit
TheTitle [boolean/text]: use a default or the given dialog title
ThePrompt [boolean/text]: use a default or the given prompt text
returns [list]: a list of the edited items, or {} if error
set {TheItems, TheInput, TheCount} to {{}, {}, (count SomeItems)}
if TheCount is less than 1 then return {} -- error
if ThePrompt is in {true, false} then -- "with" or "without" Prompt
if ThePrompt then
set ThePrompt to "Edit the following items:" & return -- default
else
set ThePrompt to ""
end if
else -- fix up the given prompt a little
set ThePrompt to ThePrompt & return
end if
if TheTitle is in {true, false} then if TheTitle then -- "with" or "without" Title
set TheTitle to "Multiple Edit Dialog" -- default
else
set TheTitle to ""
end if
set {TempTID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, return}
set {SomeItems, AppleScript's text item delimiters} to {SomeItems as text, TempTID}
set TheInput to paragraphs of text returned of (display dialog ThePrompt with title TheTitle default answer SomeItems)
repeat with AnItem from 1 to TheCount -- pad/truncate entered items
try
set the end of TheItems to (item AnItem of TheInput)
on error
set the end of TheItems to ""
end try
end repeat
return TheItems
end EditItems
to ReplaceText of SomeText from OldItem to NewItem
replace all occurances of OldItem with NewItem
parameters - SomeText [text]: the text containing the item(s) to change
OldItem [text]: the item to be replaced
NewItem [text]: the item to replace with
returns [text]: the text with the item(s) replaced
set SomeText to SomeText as text
if SomeText contains OldItem then
set {TempTID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, OldItem}
try
set {ItemList, AppleScript's text item delimiters} to {text items of SomeText, NewItem}
set {SomeText, AppleScript's text item delimiters} to {ItemList as text, TempTID}
on error ErrorMessage number ErrorNumber -- oops
set AppleScript's text item delimiters to TempTID
error ErrorMessage number ErrorNumber
end try
end if
return SomeText
end ReplaceText
to ChangeCase of SomeText to CaseType
changes the case or capitalization of SomeText to the specified CaseType using Python
parameters - SomeText [text]: the text to change
CaseType [text]: the type of case desired:
"upper" = all uppercase text
"lower" = all lowercase text
"title" = uppercase character at start of each word, otherwise lowercase
"capitalize" = capitalize the first character of the text, otherwise lowercase
returns [text]: the changed text
set SomeText to SomeText as text
if CaseType is not in {"upper", "lower", "title", "capitalize"} then return SomeText
return (do shell script "/usr/bin/python -c \"import sys; print unicode(sys.argv[1], 'utf8')." & CaseType & "().encode('utf8')\" " & quoted form of SomeText)
end ChangeCase
</pre>
Edit: how does the choose from list dialog handle those big strings? I'm guessing not very well - is that why you avoided using them?
Message was edited by: red_menace -
How do I create a multiple find and replace for Excel in AppleScript?
I have a large dataset in Excel that I have to do a multiple find/replace in (changing USPS state abbreviations to their full names). In searching the Microsoft boards--I was directed to use Applescript, and even the documented help with Excel was recommeding this. Unfortunately, there wasn't much help potinting me in the specific direction I needed. Any ideas on how I should write this script?
Thanks!I'm confused as to why Applescript (or any script would be helpful).
You'd have to type the abbreviation and the full name into the script, the same as just using Find and Replace All. You wouldn't gain anything by using a script. Is there more to this task than you've let on?
MacTech has an article on converting from VBA to Applescript, but I'm not sure if it would have any ideas on your specific problem: http://www.mactech.com/vba-transition-guide/index-toc.html -
Find and Replace text in files
Is there a function that will find and replace a word in a few text files at once. E.G replace the word database1 with database2 without going into each script individually and doing and search and replace.
Andrew, you are being so cruel, hardnuts indeed ;)
I won't mention any names, but at least it's not as cruel as some people saying “You may read DBMS_STATS package specification, at least, to get details, if you're too lazy to read manuals.”
Personally I prefer to use a development tool (TOAD, Pl/Sql Developer) instead of a Text type editor.
Maybe you are looking for
-
Error while selecting entity for composantEO
Hi, Briefly, I do an example of displaying a list of components (and already it works properly), but when I added a link to the removal of components I have encountered an error Voila details function code delete public void deleteComposantMethod(Str
-
I'm creating a pdf portfolio for the first time on a trial edition of acrobat xi pro. I've added tiff images and word docs to my portfolio, but when I try (as directed in the tutorial videos) to re-order my files by dragging and dropping them in the
-
Hi, I have purchased asset in 01.11.2008 dep need to be calculated from this date configration is required for the above issue Thanks and Regards Radha
-
How to let to manage Muse's website by client
I need to create a site. No problem with Muse, ok... but my client want to upload content (news, image... ) by himself. How can i do? Thanks to all.
-
[Web Player] Lite version of the Web Player
Web player of spotify in it full glory can be hogging more than 500 MB. Can there be a thinner more tamed version of the player, which just has a flash player and may be a playlist with a search bar. It can be thought of as a mobile version of the s