You have a whole host of problems with your code. I'm too tired to list them all, but there is one issue that is extremely difficult to solve with pure batch - there is no simple way to replace an =
literal within a string using batch. The simplest (and perhaps most effective) way to accomplish this is to look character by character for the =
and replace it via substring operations.
There are a bunch of other issues that require advanced batch techniques to solve.
I have a much simpler solution for you - my JREN.BAT utility uses regular expression replacement to rename files. It is a hybrid JScript/batch script that runs natively on any Windows machine from XP onward. Use jren /?
from the command line to access the built-in help. You might want to use
jren /? | more
to see one screen at a time. I never use MORE because my console is configured with a large buffer that lets me scroll up to see past output.
Once you have JREN.BAT on your machine, preferably in a folder that is within your PATH variable, then all you need is the following to rename the files within the current directory - no additional batch script required:
jren "[!_=%]" "-" /fm *.txt
If needed, you can specify the folder as an option:
jren "[!_=%]" "-" /fm *.txt /p "c:YourPathHere"
If you put the command within another batch script, then you will need to use CALL JREN, and the percent needs to be double escaped as %%%%
. Percent literals must be escaped as %%
within batch files, and the CALL requires an extra round of escape:
@echo off
call jren "[!_=%%%%]" "-" /fm *.txt /p "%~dp0hidden-files"
Update in response to comment
Adding (
, )
, [
, and ]
to the list of characters to replace is simple. The only trick is you must escape the ]
as ]
when it appears within a character set [....]
.
@echo off
call jren "[!_=%%%%[]()]" "-" /fm *.txt /p "%~dp0hidden-files"
The other option is to place the ]
immediately after the opening [
.
@echo off
call jren "[]!_=%%%%[()]" "-" /fm *.txt /p "%~dp0hidden-files"
Regular expressions are incredibly powerful, but they can be confusing to the uninitiated. Use jren /?regex
to access Microsoft's help page on all the supported regular expression syntax. There are loads of tutorials available on the internet, as well as web sites that allow you to conveniently test out regular expressions.
If you are developing a JREN command, I suggest you first use the /t
option to test it out without actually renaming anything.
Last update for question in comment
File names cannot contain *
, ?
, |
, <
, >
,
, /
, :
or "
, so you don't need to worry about those characters. I'm not sure what you did, but I don't see the enclosing [...]
to represent a character set. The following should work fine:
call jren "[`~!@#$%%%%^&_ +=,';}{[]()]" "-" /fm *.txt /p "%~dp0hidden-files"