批处理文件:如何替换“="(等号)和一个字符串变量? [英] Batch file: How to replace "=" (equal signs) and a string variable?

查看:20
本文介绍了批处理文件:如何替换“="(等号)和一个字符串变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了SED,等号怎么替换?以及如何在字符串替换中使用字符串变量?

Besides SED, how can an equal sign be replaced? And how can I use a string variable in string replacement?

考虑这个例子:

For /F "tokens=*" %%B IN (test.txt) DO (
   SETLOCAL ENABLEDELAYEDEXPANSION
   SET t=is
   SET old=%%B
   SET new=!old:t=!
   ECHO !new!

   ENDLOCAL
)

:: SET new=!old:==!

两个问题:

首先,我不能在 !:=! 中使用变量 %t%.

First, I cannot use the variable %t% in !:=!.

   SET t=is
   SET old=%%B
   SET new=!old:t=!

其次,我无法替换命令行中的等号

Second, I cannot replace the equal sign in the command line

   SET new=!old:==!

推荐答案

我刚刚为此自己创建了一个简单的解决方案,也许对某人有帮助.

I just created a simple solution for this myself, maybe it helps someone.

缺点(或优点,取决于您想做什么)是多个等号一个接一个地处理,就像一个等号一样.(例如:str==ing"给出与str=ing"相同的输出)

The disadvantage (or advantage, depends on what you want to do) is that multiple equal signs one after another get handled like one single equal sign. (example: "str==ing" gives the same output as "str=ing")

@echo off
set "x=this is=an test="
echo x=%x%

call :replaceEqualSign in x with _
echo x=%x%

pause&exit


:replaceEqualSign in <variable> with <newString>
    setlocal enableDelayedExpansion

        set "_s=!%~2!#"
        set "_r="

        :_replaceEqualSign
            for /F "tokens=1* delims==" %%A in ("%_s%") do (
                if not defined _r ( set "_r=%%A" ) else ( set "_r=%_r%%~4%%A" )
                set "_s=%%B"
            )
        if defined _s goto _replaceEqualSign

    endlocal&set "%~2=%_r:~0,-1%"
exit /B

如您所见,您可以像这样使用函数:

As you have seen, you use the function like this:

call :replaceEqualSign in variableName with newString

这篇关于批处理文件:如何替换“="(等号)和一个字符串变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆