在DOS批处理字符串替换命令中转义等号

时间:2010-03-23 12:03:12

标签: string dos batch-file

我需要使用DOS批处理文件替换JNLP文件中的某些文本,以便为本地计算机调整它。

问题是搜索模式包含一个等号,这会弄乱批处理文件中的字符串替换。

我想替换这行,

<j2se version="1.5" initial-heap-size="100M" max-heap-size="100M"/>

具有初始和最大堆大小的特定设置。

例如我现在的时候,

for /f "tokens=* delims=" %%a in (%filePath%agility.jnlp) do (
set str=%%a
set str=!str:initial-heap-size="100M"=initial-heap-size="%min%M"!
echo !str!>>%filePath%new.jnlp)

但搜索模式中的=正在作为替换命令的一部分被读取。

如何转义等号以便将其作为文本处理?

4 个答案:

答案 0 :(得分:1)

最好的解决方案是下载并安装CygwinGNUWin32但是,如果您真的受限于标准命令处理器,它可能会有点混乱。

这不是世界上最快的方法,但它至少是功能性的。此命令文件一次处理每行一个字符,特别处理您找到要查找的节的情况。

@echo off
set init=50M
set max=75M
setlocal enableextensions enabledelayedexpansion
for /f "tokens=* delims=" %%a in (agility.jnlp) do (
    set str1=%%a
    call :morph
    echo !str2!>>agility_new.jnlp
    echo !str2!
)
endlocal
goto :eof

:morph
    set str2=
:morph1
    if not "x!str1!"=="x" (
        if "!str1:~0,18!"=="initial-heap-size=" (
            set str2=!str2!initial-heap-size="!init!"
            set str1=!str1:~24!
            goto :morph1
        )
        if "!str1:~0,14!"=="max-heap-size=" (
            set str2=!str2!max-heap-size="!max!"
            set str1=!str1:~20!
            goto :morph1
        )
        set str2=!str2!!str1:~0,1!
        set str1=!str1:~1!
        goto :morph1
    )
    goto :eof

使用输入文件:

<j2se version="1.5" initial-heap-size="100M" max-heap-size="100M"/>
next line
===

你最终得到:

<j2se version="1.5" initial-heap-size="50M" max-heap-size="75M"/>
next line
===

答案 1 :(得分:1)

一个人不能简单地用一个等号替换(一个子串),而不用拆分(for {statement with "delims==")或修剪......

但也许你可以在for-loop中使用以下语句来解决这个更简单但更混乱的方法:

set str=!str:"100M" max-heap-size="%min%M" max-heap-size!

它只是将字符串组合替换为之后的而非之前的,完全避免任何等号替换。

答案 2 :(得分:0)

如果您可以将参数作为其他参数传递,例如双下划线,则可以遍历它们并将它们转换为批处理文件中的“=”。

@rem Replace __ with = in batch files.
@rem This works around the lack of equals signs in args
@rem args contains full args string with substitutions in place

setlocal enabledelayedexpansion

:argloop
if "%~1" NEQ "" (

set str=%~1
set out=!str:__==!
set %~1=!out!
set args=!args!!out!

SHIFT
goto :argloop
)

@rem Can now run program on a line on its own with just %args%

来源:https://github.com/mlabbe/batchargs

答案 3 :(得分:-4)

这是另一种解决方案。如果您有能力下载GNU工具,可以使用sed

C:\test>set a=200
C:\test>sed -i.bak "s/^\(.*initial-heap-size=\"\).*\( max.*\)/\1%a%\"\2/" file