Copy link to clipboard
Copied
I've got a some images that have had numbers added to the ends of the filenames. I'd like to relink them back to the original, un-numbered file.
So,
myImage-1.jpg relinks to myImage.jpg
myImage-2.jpg relinks to myImage.jpg …
I wrote a script to run through all the links in the document, then use grep to see if an un-numbered version of that file exists for relinking, but I have to wonder: is there some quicker/better way to target individual links without running through the entire list of links to find them?
I thought to try
app.activeDocument.links.item(/myImage-\d+.jpg/)
but that doesn't work.
Thanks for any advice!
You cannot use RegExp there. You need the exact name:
var link = app.activeDocuments.itemByName("myImage-1.jpg");
if(link.isValid) lk.relink(new File("/Some/location/to/myImage.jpg");
Copy link to clipboard
Copied
You cannot use RegExp there. You need the exact name:
var link = app.activeDocuments.itemByName("myImage-1.jpg");
if(link.isValid) lk.relink(new File("/Some/location/to/myImage.jpg");
Copy link to clipboard
Copied
If you want something more "dynamic", you could loop through links and look at if their nalme matches a certain string with your regexp:
function main(){
var doc = app.documents.everyItem().getElements();
var n = doc.length;
if(!n){
alert("You need a document");
return;
}
doc = doc[0];
var lks = doc.links.everyItem().getElements(), lk;
n = lks.length;
while(n--){
lk = lks[n];
var numberedFile = File(lk.filePath);
var newFolder = numberedFile.parent;
var linkName = lk.name;
var newLinkName = linkName.replace(/-\d+\.jpg$/, ".jpg");
var newLinkFile = File(newFolder+"/"+newLinkName);
if(/myImage-\d+\.jpg/.test(linkName) && newLinkFile.exists) lk.relink(newLinkFile);
}
}
var u;
app.doScript("main();", u, u, UndoModes.ENTIRE_SCRIPT, "Relink");
Copy link to clipboard
Copied
Thanks! That's pretty much what I've been doing. I was just curious if there's a more efficient way to do it.
Actually, I've never used .test() before, so I'll look at that. Thanks again!
Copy link to clipboard
Copied
Out of curiosity, @dona56558947, is your script running slowly? It is common to loop over all the <objects> in a document and mostly doesn't cause a performance issue.
If it is too slow in the case of your document, you could try making an array of strings using app.activeDocument.links.everyItem().name and looping over that, then get the link(s) you want by using the loops index: app.activeDocument.links.item(i). I doubt that it would speed things up much, but it might.
- Mark
Copy link to clipboard
Copied
It's noticeably slower than a similar script I use to replace links with known names, but it still takes only a moment. I was just curious if there's a more efficient way to do it. Thanks!