问题
Lets say that we have 4 variables like:
set var1=Hello
set var2=Some text
set var3=Some more text
set var4=Even some more text
And then prompted to the user to delete one of them, in this case (1-4) like:
set /p delete_one="Delete one:"
And if the user wrote for example "2" the new variables would be:
var1=Hello
var2=Some more text
var3=Even some more text
How would i make this work?
回答1:
@echo off
setlocal EnableDelayedExpansion
set var1=Hello
set var2=Some text
set var3=Some more text
set var4=Even some more text
SET VAR
set /p delete_one="Delete one: "
set "Xvar="
for /F "tokens=1,2 delims==" %%a in ('set var') do (
if defined Xvar (
set "!Xvar!=%%b"
set "Xvar=%%a"
) else if "%%a" equ "var%delete_one%" (
set "Xvar=%%a"
)
)
set "%Xvar%="
SET VAR
You must check that the given number of variable to delete exists. Note that variables are sorted alphabetically, so if more than 9 variables exists, and you want to preserve its "natural order", variables less than 10 must have a left zero: var01=Hello
and you have to give this left-zero value to delete that variable.
回答2:
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
set var1=Hello
set var2=Some text
set var3=Some more text
set var4=Even some more text
FOR /L %%a IN (5,1,12) DO SET var%%a=MORE text %%a
SET VAR
set /p delete_one="Delete one: "
SET /a get=1
SET /a put=1
:loop
IF %get%==%delete_one% SET /a get+=1
IF %get%==%put% GOTO next
SET var%put%=!var%get%!
:next
SET /a put+=1
SET /a get+=1
IF DEFINED var%get% GOTO loop
SET "var%put%="
SET VAR
GOTO :EOF
...Immune to limit-of-9.
来源:https://stackoverflow.com/questions/24103920/delete-and-replace-variables