删除和替换变量

时间:2014-06-08 07:23:36

标签: batch-file cmd command-prompt

让我们说我们有4个变量,如:

set var1=Hello
set var2=Some text
set var3=Some more text
set var4=Even some more text

然后提示用户删除其中一个,在本例中为(1-4),如:

set /p delete_one="Delete one:"

如果用户编写例如“2”,则新变量将为:

var1=Hello
var2=Some more text
var3=Even some more text 

我将如何使这项工作?

2 个答案:

答案 0 :(得分:0)

@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

您必须检查是否存在要删除的给定变量数。请注意,变量按字母顺序排序,因此如果存在多于9个变量,并且您希望保留其“自然顺序”,则小于10的变量必须保留左半:var01=Hello并且您必须将此左值设为零删除该变量的值。

答案 1 :(得分:0)

@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

......免疫限制为9。