Remove keywords (from a file) for all files in list.

I have been trying to use Advanced Renamer for my simple use case but I have hit a wall. My situation and use case seems simple.

I have a text file with a list of over 200 keywords, each keyword is on it's own line. All I need is for AR to access that list of keywords and then remove any keywords in that list from any and all file names in my file list.

I came to the conclusion that this task has to be done via the scripting method with AR, there is no other way (correct me if I'm wrong). So, I used the following script and AR gave the the error "ReferenceError: ActiveXObject is not defined"

Below is the script I used. I am at a loss and would appreciate some help either modifying this script to work or use another method to (quickly) get this simple task done in AR.

// Load keywords from external text file
var fso = new ActiveXObject("Scripting.FileSystemObject");
var file = fso.OpenTextFile("X:\\path\to\keywords.file", 1);
var keywords = [];
while (!file.AtEndOfStream) {
var line = file.ReadLine();
if (line.length > 0) {
keywords.push(line);
}
}
file.Close();

// Function called for each filename
function rename(name) {
for (var i = 0; i < keywords.length; i++) {
var kw = keywords[i];
// Remove *all* occurrences of the keyword anywhere in the filename
while (name.indexOf(kw) !== -1) {
name = name.replace(kw, "");
}
}
return name; // cleaned filename
}



Thanks.

EDIT: I also just tried the following script and get error "ReferenceError: File is not defined ", but the file is defined.


// Read the content of your keyword file
var keywordsFile = "X:\\path\to\keywords.file";
var keywordsContent = File.read(keywordsFile);
var keywords = keywordsContent.split('\n').map(function(line) {
return line.trim(); // Remove leading/trailing whitespace
}).filter(function(line) {
return line.length > 0; // Filter out empty lines
});

// Get the current filename
var newFileName = item.newName;

// Iterate through keywords and remove them
for (var i = 0; i < keywords.length; i++) {
var keyword = keywords[i];
// Use a regular expression to replace all occurrences of the keyword
// The 'g' flag ensures all occurrences are replaced, 'i' for case-insensitivity if desired
var regex = new RegExp(keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi'); // Escape special characters for regex
newFileName = newFileName.replace(regex, "");
}

// Set the new filename
return newFileName;
Reply to #1:

Note that Aren JS is closer to pure ECMAScript. It doesn't have (all of) the extra APIs of a browser -- and certainly not Node.js.

But it *does* have a readFileLines function ( https://www.advancedrenamer.com/user_guide/v4/method_script ).

Here's how to use it for your task:

1) Paste this as a "Pre batch script":
//----------------------------------------------------
//-- You must escape slashes in the file path:
badwordsArry = app.readFileLines ("C:\\Temp\\aren foo\\_test\\badwords.txt");
badwordsArry = badwordsArry.filter (zWord => zWord != ""); // Need to strip empty lines.

badwordsRegx = badwordsArry.map (zWord => {
let purePhrase = zWord.replace (/\r|\n/g, ""); // readFileLines leaves line endings in array
return new RegExp (`${purePhrase}`, "ig");
} );
/* For debug:
console.log (badwordsArry);
console.log (badwordsRegx[0].toString() );
//*/
//----------------------------------------------------

2) Then for the regular (per file) script, use:
//----------------------------------------------------
let fName = item.newBasename;

badwordsRegx.forEach (zRegx => fName = fName.replace(zRegx, "") );

return fName;
//----------------------------------------------------

Regards,
Randy

ETA: Also be sure that your external file's extension is allowed in:
Settings -> JS Script editor -> Allowed extensions for reading content from files

Update: Rolled in the patch from post 4 to 100% fulfill the OP's changed requirement.
Reply to #2:

Thanks for your time.

Your script doesn't entirely work for me. I didn't mention that all the keywords in my list end in a comma and space (ie. keyword, ).

I never ran into a problem when keywords are at the beginning of a filename. The problem is with keywords in the middle or end of a file name and it seems totally random.

The fact that my keywords in my file all have a trailing comma and space obviously matters because if remove the comma and space from the keywords in my list your script runs fine (obviously the comma and space are not removed, though).

However with my keyword list left as is, here are the combinations that do and don't work.

Keywords are removed in the following situations:

- word keyword, word - word.ext

- keyword, keyword, .ext (both keyword instances are removed)

- keyword1, keyword2, .ext (both keywords are removed)

- keyword, word - keyword, word.ext (both keyword instances are removed)

- word keyword, word.ext

- word, keyword, - word.ext



Keywords are not removed in these situations:

- word, keyword, - keyword, word.ext (only second keyword instance is removed)

- word, keyword1, - keyword2, word.ext (neither keyword is removed)

- word - keyword, - word.ext

- word, keyword, - word.ext


I see no logic as to why it works and why it doesn't.


Log shows...

"keyword1, \r",
"keyword2, \r",
"keyword3, \r",
"keyword4, \r",
"keyword5, \r",
"keyword6, \r",
]
/\bkeyword1, \b/gi
Reply to #3:

Okay, if I read you correctly, you *do* want the comma and space removed from the filename, right?

Anywho, change the return line to:
return new RegExp (`${purePhrase}`, "ig");

The trailing \b in the regex was literally hitting a (word) edge case. Pun intended ;)

But, since you can use regex yourself in the badwords file, you can specify \b, etc. there -- if it is ever needed for your particulars.

Speaking of which, if your badwords file really contains: "keyword1, ", "keyword2, ", "keyword3, ", etc.
You could replace all that with a single line of "keyword\d, " . -- Using the JS regex token
Reply to #4:

Oh no, I don't want to remove the comma plus space in my keywods list. AR needs to find those keywords with the comma and space in order to remove not just the keywords but also the trailing comma and space.

At any rate, I finally got Copliot AI to make me a script that actually works in AR. That was an extremely frustrating experience lol.

I have not used it much but I will be hopefully before end of the month.


//Pre batch script
//------------------

var keywordsList = []; // Initialize a global variable

// Use app.readFileLines() which is the correct function
var filePath = "C:\\path\\to\\file.txt";
var lines = app.readFileLines(filePath);

if (lines) {
// Process the lines into the global keywordsList array
keywordsList = lines.map(function(line) {
return line.trim();
}).filter(function(line) {
return line.length > 0;
});
} else {
// Optional: Log an error message if file reading fails
app.log("Error reading keywords file or file is empty: " + filePath);
}



//Main script
//------------

// Work on the basename (without extension)
var newName = item.newBasename;

// Helper: escape regex special chars
function escapeRegExp(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

keywordsList.forEach(function (keyword) {
if (!keyword) return;

// Escape keyword for regex
var kw = escapeRegExp(keyword);

// Pattern: match the keyword itself, plus an optional trailing comma+space
// BUT do not consume spaces before the keyword
var regex = new RegExp(kw + '(?:,\\s*)?', 'gi');

newName = newName.replace(regex, '');
});

// Normalize: collapse multiple spaces, trim ends
newName = newName.replace(/\s{2,}/g, ' ').trim();

return newName;
...
Reply to #6:

What we have here is a failure to communicate...

Larry, glad you got what you needed. Next time you might get more targeted and useful help if you specify the problem more clearly.

As someone who has spent a lot of time answering questions here, I can honestly say that if the question-asker can provide a complete description of the problem, we can almost always answer the first time. Granted, that answer may be "that's not an Advanced Renamer problem" or "there's a better way to do what you are asking", but at least we have a shot at answering. The more vague the problem description, the more time wasted, the more backtracking, the more re-writing and re-figuring the answer. In other words, without knowing what we are trying to fix there's pretty much no way in hell we can give a useful answer.

Please don't think I'm singling you out, this happens waaay too often here. This is really meant for anyone posting questions, but there's no way to make a post "sticky" so I can basically only talk to you right now. Additionally I know there can be language problems, and that can't always be helped.

Anyway, as I said, I'm glad you have an answer to your problem...

Best,
DF
Reply to #7:

Thanks DF. I feel heard (^_^)

Reply to #8:

Yeah, when I read your blank post I knew it had to be said...

Completely off-topic, that emoji you just used looks just like the front end of my Corvette. Which I why I named her Emoji. LOL

Not a view people get in their rear-view mirrors very long... :)
Reply to #9:

I totally understand issues with helping people without enough information. But posting on forums is a double-edged sword. When you post too little information, that never works. But on the flipside, given the fast society we live in, posting long forum posts usually doesn't work out either because information gets skimmed over or ignored. Just the way it is.

At any rate. I feel like someone is angry here and I see no reason for it. I'm not angry. I did not angrily go to AI because Randy's script didn't work for me. I had already been (painstakingly) working with AI for many hours before I even posted here. It took so @#&%#-ing many iterations to get a working script from AI and it was one frustrating experience, that and I find Copilot to be utterly and annoyingly arrogant when it gets something wrong lol. It understood my problem and the solution (I think), but writing an AR script for it was apparently not it's forte, lol. In fact, it only finally worked out because I used info from another AI to correct the one that was actually writing the script.

Anyhow, no hard feelings on my end. Sorry if I pissed someone off. Dealing with the public never was, is not and never will be a non-frustrating endeavor, though.
Reply to #10:

Hi Larry,

Nobody is angry here, believe me. It's just that , well, we *aren't* AI, so as actual humans we get frustrated as well. :) I was not being passive aggressive when I said I was glad you had a solution. I *was* trying to explain in part why the process broke down here. And I think you'll find that the people who spend time here, working on solutions, try to be thorough in understanding the problems of the people we encounter. I'm pretty sure most of us have been around long enough that we weren't raised with the 15-second attention span engendered by tiktok videos. LOL

Just a suggestion, when posting a question,
1. provide the actual format of the input, in enough detail so that we can get a clear picture. Obviously if it is sensitive information you need to obfuscate, but a clear picture of in your case the input file structure and your filename structures would have helped prevent the "Oh by the way all the keywords end in comma and space" problem.
2. And of course, the exact format of the filenames you want on completion.

I've read the thread several times and still don't have a clear picture of any of that. It may well be that you could accomplish what you need just by importing your file as a csv, and not even need scripting.

I know emotions don't really convey in a text thread, but I do want to stress that I'm pretty certain no one is upset here. I think I can speak for the others here when I wish you only the best.

Best regards, warm wishes for the holidays my friend,
DF
Reply to #11:

Hey, no prob, delta. And glad that no one is angry/mad whatever.