4
set var=this-is-a-test

ECHO I would like to convert the value of this variable to "this%_%is%_%a%_%test"

I tried with:

SET VAR=%VAR:-=%_%%

But doesn't work :(

Please help

David
  • 41
  • 1
  • 1
  • 2

1 Answers1

5

Because of the way percents are used for variables it messes up what you are trying to do. One way around this is with delayed expansion. You also have to escape the percent by putting two of them in a row %%.

Something like:

Setlocal EnableDelayedExpansion
set _name=s-t-r-i-n-g
set _name=!_name:-=%%_%%!
echo %_name%
Confuzing
  • 551
  • 2
  • 9
  • (1) It’s good manners to answer the question that was asked, *as* it was asked.  The question contains a perfectly good variable assignment; why did you change the variable’s name and its value?  (2) I doubt that anybody who has this question would need to be told to use `echo` to display the value of a variable.  If you’re trying to demonstrate your solution in action, fine; but then show *the output* from the `echo`.  (3) I guess you didn’t show the output because ```s%_%t%_%r%_%i%_%n%_%g``` is too ugly for the human eye to process.  … (Cont’d) – Scott - Слава Україні Mar 20 '20 at 03:03
  • (Cont’d) …  But that’s all the more reason for sticking with the OP’s value.  (4) Since the question ***contains*** **`_`**, it is unnecessarily confusing that you gratuitously added a **`_`** to the variable name.  (5) Even though the question is tagged “batch” and “batch-file”, it would be nice to point out that these commands will not work in an interactive Command Prompt. … … … … … … … … … … … … … … Please do not respond in comments; [edit] your answer to make it clearer and more complete. – Scott - Слава Україні Mar 20 '20 at 03:03