Samuel Nguyen
Samuel Nguyen

Reputation: 29

Batch String Manipulation

I am trying to write a batch program that writes more code based on what the user inputs. I am stuck on the string manipulation, as "!", ">", "&", and "%" all need to be escapeded before they are to be outputted to other files. This is what I have so far:

@echo off
set /p code=
set newcode=%code:^%=^%%,^>=^^>,!=^^!,^&=^^&%
echo %newcode%>>file.bat

All this escapinging escaped stuff is making my brain hurt, so can you please help me?

Thanks!

Upvotes: 1

Views: 558

Answers (2)

jeb
jeb

Reputation: 82420

Simply use delayed expansion in your case, as delayed expansion needs no further escaping for the content.

@echo off
setlocal EnableDelayedExpansion
set /p code=
echo(!code!

The echo( is for safe text output, even if the text is empty or is something like /?.

To the comment of @foxidrive:
When delayed expansion is enabled, then exclamation marks ! are altered, when they are visible before the delayed expansion is done, but the expanded content of delayed expanded variables will never be altered.

@echo off
set "var=Hello!"
setlocal EnableDelayedExpansion    
echo "!var!" "Hello!"

This will result to: "Hello!" "Hello"

Upvotes: 2

Monacraft
Monacraft

Reputation: 6620

Since you haven't explained clearly what you are trying to do with the input, I am assuming you are trying to get the user to type something and then for that to be entered into a file. If that is the case te utilise copy in combination with con

@echo off
Echo Enter ^^Z (Ctrl + Z) and return it to end input
copy con file.txt

And that will allow the user to type WHATEVER they want, and it to be put in a file to be examined. Otherwise you're gonna have a lot of fun (And trouble) dealing with all the escaping you're gonna have to do (Rather ironic wasn't that?).

Mona.

Upvotes: 3

Related Questions