ryuh wrote:foxidrive wrote:When you execute your batch file this first line changes a to z. Then when the last line runs it changes z back to a.
set "text=!text:a=z!"
set "text=!text:z=a!"
That makes sense.. but how would it be fixed? Should I add another variable to separate the 2 groups of letters? a-m, n-z?
You must differentiate the "z" letter used to replace the "a" from any other "z" letter that may appear in the text, that is, you must use a
different character for the first replacement and, after replaced the original "z", replace again the different character to "z". The example below use the digits 0..9 and #$/ characters to replace the letters a..m, and replace such characters back to letters n..z at end:
Code: Select all
@echo off
setlocal EnableDelayedExpansion
set text=abcdefghijklmnopqrstuvwxyz
set "text=!text:a=0!"
set "text=!text:b=1!"
set "text=!text:c=2!"
set "text=!text:d=3!"
set "text=!text:e=4!"
set "text=!text:f=5!"
set "text=!text:g=6!"
set "text=!text:h=7!"
set "text=!text:i=8!"
set "text=!text:j=9!"
set "text=!text:k=#!"
set "text=!text:l=$!"
set "text=!text:m=/!"
set "text=!text:n=m!"
set "text=!text:o=l!"
set "text=!text:p=k!"
set "text=!text:q=j!"
set "text=!text:r=i!"
set "text=!text:s=h!"
set "text=!text:t=g!"
set "text=!text:u=f!"
set "text=!text:v=e!"
set "text=!text:w=d!"
set "text=!text:x=c!
set "text=!text:y=b!"
set "text=!text:z=a!"
set "text=!text:0=z!"
set "text=!text:1=y!"
set "text=!text:2=x!"
set "text=!text:3=w!"
set "text=!text:4=v!"
set "text=!text:5=u!"
set "text=!text:6=t!"
set "text=!text:7=s!"
set "text=!text:8=r!"
set "text=!text:9=q!"
set "text=!text:#=p!"
set "text=!text:$=o!"
set "text=!text:/=n!"
echo %text%
Of course, this method prevents that the original text may include anyone of the characters used in the replacement...
If you want that the text include any character, then the conversion must be performed
character by character so converted characters will not be processed again.
Code: Select all
@echo off
setlocal EnableDelayedExpansion
rem Create the replacement array
set letter=abcdefghijklmnopqrstuvwxyz
for /L %%i in (0,1,25) do (
set /A j=25-%%i
for %%j in (!j!) do set "replace["!letter:~%%i,1!"]=!letter:~%%j,1!"
)
set "text=0123456789 %letter% #$&/()[]"
echo Original: !text!
rem Separate the text in individual characters, and convert each one
set "result="
for /F "delims=" %%a in ('cmd /U /C set /P "=!text!" ^< NUL ^| find /V ""') do (
if defined replace["%%a"] (
set "result=!result!!replace["%%a"]!"
) else (
set "result=!result!%%a!
)
)
echo Replaced: !result!
Previous Batch file use a trick (documented elsewhere) that execute "cmd /U" to create Unicode characters, that is, each character will be separated from the next one with a zero byte, so find command can take each character individually. The conversion is done via an array in a direct way.
Antonio