且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

删除并替换变量

更新时间:2023-02-19 14:03:50

 关闭@echo
SETLOCAL EnableDelayedExpansion设置VAR1 =您好
集VAR2 =某些文本
集VAR3 =一些文字
集VAR4 =甚至一些文字SET VAR集/ p delete_one =删除了一句:设置XVAR =
FOR / F令牌= 1,2 delims ==%%一中(设置VAR')做(
   如果定义XVAR(
      集!XVAR!= %% B
      设置XVAR = %%一个
   )否则,如果%%一个EQUVAR%delete_one%(
      设置XVAR = %%一个
   )

集%XVAR%=SET VAR

您必须检查删除变量给定数量的存在。需要注意的是变量是按字母顺序排序,因此,如果超过9个变量存在,并且要preserve其自然秩序,变量低于10必须​​有一个左零: var01 =您好,你必须给这个左零值来删除该变量。

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?

@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.