Interesting challenge.
I've succeeded in surpassing your original requirements
Here is a command line one liner that does not use any true environment variable, though it does use the dynamic pseudo environment variable %cmdcmdline%. Since it is command line, it obviously cannot use GOTO.
Code: Select all
cmd /c "@(call &for %F in ("* *.txt") do @for /f "tokens=1* delims= " %A in ("%F") do @if not "%B"=="" (ren "%F" "%A_%B"&call))&if not errorlevel 1 %^cmdcmdline%"
There are a couple odd restrictions with the above that I do not understand:
1) If the command does not rename any files, then the following unfortunate error message is generated, though I haven't seen any negative impact beyond the message
Code: Select all
'%cmdcmdline%' is not recognized as an internal or external command,
operable program or batch file.
2) The command does not loop properly if the file mask is
"*"or
"*.*"
It only works properly if the file mask has some restriction. For example,
"*.txt" works, as does
"* *"
Obviously the code could be adapted for use in a batch file.
renSpaceTo_.bat
Code: Select all
@cmd /c "(call &for %%F in (%*) do @for /f "tokens=1* delims= " %%A in ("%%F") do @if not "%%B"=="" (ren "%%F" "%%A_%%B"&call))&if not errorlevel 1 %%cmdcmdline%%"
Now the code is parametized, and
%* allows you to specify multiple file masks.
For example, the following works perfectly without error as long as at least one file is renamed
Next I thought, why not make a DOSKEY macro variant.
I first tried the obvious:
Code: Select all
doskey renSpaceTo_=cmd /c "@(call &for %F in ($*) do @for /f "tokens=1* delims= " %A in ("%F") do @if not "%B"=="" (ren "%F" "%A_%B"&call))&if not errorlevel 1 %^cmdcmdline%"
But there is a mysterious quoting anomaly that drops a quote from the first IF comparison.
Code: Select all
C:\test>doskey /macros
renSpaceTo_=cmd /c "@(call &for %F in ($*) do @for /f "tokens=1* delims= " %A in ("%F") do @if not "%B"==" (ren "%F" "%A_%B"&call))&if not errorlevel 1 %^cmdcmdline%"
I managed to find a solution, substitute 3 quotes for the 1 quote that was getting dropped. But I have no idea why this works.
Code: Select all
doskey renSpaceTo_=cmd /c "@(call &for %F in ($*) do @for /f "tokens=1* delims= " %A in ("%F") do @if not "%B"=="""" (ren "%F" "%A_%B"&call))&if not errorlevel 1 %^cmdcmdline%"
$* works just like the batch
%*, so the macro also supports multiple file masks.
Of course both the batch file and macro have the same restrictions as the original command one liner.
I'm curious if anyone can figure out the reason behind the restrictions, or why the macro requires the 2 extra quotes.
Dave Benham