convert user input character by character with batch

1.2k Views Asked by At

ok basicly i want a simple batch program to change X characters to Y characters in a way like this

a-b
b-c
c-d
d-e
e-f
etc etc etc

ive looks up strings and other variable tricks but it doesnt work. heres what i tried and you can see on "codeb" where i tried an alternate method

set /p code=[paste your code here]
set code=%codea:~1%
set /a %code:~2% %codeb%

this was basically my way of attempting to split all the input characters into seperate variables.

if your feeling....bored below is the exact conversion for the translation

a='
b=v
c=x
d=s
e=w
f=d
g=f
h=g
i=u
j=h
k=j
l=k
m=n
n=b
o=i
p=o
q=\
r=e
s=a
t=r
u=y
v=c
w=q
x=z
y=t
z=/

essentially i should be able to "paste" this "v'rxg" into the batch and hit enter and it then displays "batch"

2

There are 2 best solutions below

0
On

Well, here's a working script that you can play with. It uses your chart in the form of a text file (named codechart.txt in my setup):

@ECHO OFF
:loop
SET /P encoded=[paste your code here]
IF [%encoded%]==[] GOTO :EOF
SET decoded=
CALL :decode
ECHO Result:
ECHO(%decoded%
GOTO loop

:decode
IF [%encoded%]==[] GOTO :EOF
SET ec=%encoded:~0,1%
SET encoded=%encoded:~1%
SET dc=?
FOR /F "delims==" %%C IN ('FIND "=%ec%" ^<codechart.txt') DO SET dc=%%C
SET decoded=%decoded%%dc%
GOTO decode

If you enter a non-empty string, it will produce a result. Hitting Enter without actually entering anything will terminate the batch. If a character is not found in the chart, it will be represented as a ? in the output.

1
On

I modified Andriy's code for a faster version that use Batch variables instead of FIND text file. Here it is:

@echo off
setlocal EnableDelayedExpansion
for /f "delims=" %%a in (codechart.txt) do set %%a
:loop
set /P encoded=[paste your code here]
if "%encoded%" == "" goto :eof
set decoded=
call :decode
echo Result:
echo\%decoded%
goto loop

:decode
if "%encoded%" == "" goto :eof
set ec=%encoded:~0,1%
set encoded=%encoded:~1%
set dc=?
if defined %ec% set dc=!%ec%!
set decoded=%decoded%%dc%
goto decode

However, my version does not work when special characters (non-valid variable names) are encoded.

EDIT The only differences of my code vs. Andriy's are these:

  • setlocal EnableDelayedExpansion: This command is required to use !var! expansion besides %var%, allowing to use both expansions in the same command.
  • for /f "delims=" %%a in (codechart.txt) do set %%a: This command takes the lines of your conversions and execute a set command with each one, that is, set a=' set b=v etc. This way, the conversions are stored in Batch variables with the name of the original character and the value of the new character.
  • if defined %ec% set dc=!%ec%!: This line convert the character in ec variable via a direct replacement. For instance, if ec is "b": if defined b set dc=!b!; because b variable exists and contains a "v", then execute set dc=v.