如何在批处理脚本中查找字符串并将其替换为另一个字符串? [英] How can I find and replace string with another string in batch script?

查看:110
本文介绍了如何在批处理脚本中查找字符串并将其替换为另一个字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试查找字符串并将其替换为文件中的另一个字符串.

I am trying to find and replace string with another string in a file.

我有一个XML文件,其中port=存在于多个位置.每个端口都有不同的值,例如port="443"port="8011".

I have an XML file where port= is present at multiple locations. Every port has different value like port="443" and port="8011".

我想找到一个特定的port及其值. port的当前值在批量执行时未知,因为该值会变化.此变量以及XML文件中一个特定port属性的未知值在批处理执行时应替换为我作为参数传递给批处理文件的新值.

I want to find a particular port and its value. The current value of port is not known on batch execution as the value varies. This variable and on batch execution unknown value of one specific port attribute in the XML file should be replaced with a new value I am passing as a parameter to the batch file.

如何从文件中找到特定的port值并将其替换为新值?

How can I find the particular port value from a file and replace it with a new value?

我已使用以下代码替换字符串,但无法更改其值.

I have used the below code for replace string, but I am not able to change its value.

if EXIST %ConfPath% (echo "here") ELSE (
    for /f "tokens=1,* delims=¶" %%A in ( '"type %file%"' ) do (
        SET string=%%A

        SET modified=!string:%oldport%=%newport%!

        echo !modified! 
    )
)

这是我的XML文件:

<?xml version='1.0' encoding='utf-8'?> 
<Server port="first" shutdown="SHUTDOWN">  
<Listener className="org.apache.catalina.core.JasperListener" /> 
<Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" /> 
<Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" /> 
<Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" /> 
<GlobalNamingResources> 
<Resource name="UserDatabase" auth="Container" type="org.apache.catalina.UserDatabase" description="User database that can be updated and saved" factory="org.apache.catalina.users.MemoryUserDatabaseFactory" pathname="conf/tomcat-users.xml" /> 
</GlobalNamingResources> 
<Service name="Catalina">  
<Connector port="second" redirectPort="forth" /> 
<Connector port="third" protocol="HTTP/1.1" SSLEnabled="true" scheme="https" secure="true" clientAuth="false" sslProtocol="TLS" URIEncoding="UTF-8" keystoreFile="myKey" keystorePass="myPass" /> 
</Service> 
</Server> 

上面的文件中有四个端口.

There are four ports present in above file.

我想用port="newPort"更改port="third".

直到现在我已替换了字符串,但无法将其与其余文件连接起来.

Until now I have replaced the string, but I'm not able to concatenate it with the remaining file.

首先我得到行号,然后我用引号将其分开并替换.但是我无法将其连接起来.缺少某些东西,但我找不到它.

First I get the line number and after that I split with quotes and replace. But I I'm not able to concatenate it. Something is missing but I cannot find it.

我的批处理代码是:

for /f "tokens=1,* delims=" %%A in ( '"type %file%"' ) do (
    SET /a line+=1
    IF !line!==11 (
        SET string=%%A
        for /f tokens^=2^ delims^=^" %%I in ( "!string!" ) do (set repPort=%%I)
        SET modified=!string:repPort=PORT!
    )
    echo !modified!
)

这是正确的方法,如何连接?

Is this the right approach and how can I concatenate?

推荐答案

如何使用Windows命令在文件中查找和替换文本行环境?列出了几种用于从命令行替换文件中字符串的工具.

How can you find and replace text in a file using the Windows command-line environment? lists several tools for replacing a string in a file from command line.

我喜欢免费的控制台工具 xchang32.exe ,因为它功能强大且易于使用.

I like free console tool xchang32.exe as it is powerful and very easy to use.

我将您的XML文件的内容复制到一个文件中,并将其保存为名称 Test.xml .

I copied the content of your XML file into a file and saved it with name Test.xml.

然后我执行了以下命令:

Then I executed following command:

xchang32.exe Test.xml "port=^34third^34 protocol" "port=^34newPort^34 protocol"

该命令仅在文件中更改

<Connector port="third" protocol="HTTP/1.1" SSLEnabled="..." /> 

<Connector port="newPort" protocol="HTTP/1.1" SSLEnabled="..." /> 

^34是双引号字符"的转义序列,其十进制代码值为34.

^34 is an escape sequence for double quote character " which has decimal code value 34.

xchang32.exe /?会输出此替换工具的帮助.

xchang32.exe /? entered and executed in a command prompt window outputs help for this replace tool.

当然,您也可以使用在引用的主题中建议的任何其他方法.您只需要在搜索中包含 protocol 并替换字符串即可仅修改应修改的端口号,而忽略其他所有端口号.仅使用Windows标准命令的解决方案更加困难,因为XML文件中的字符<>"在命令行上具有特殊含义.

Of course you could use also any other method suggested in the referenced topic. You just need to include protocol in search and replace string to modify just the port number which should be modified and ignore all other. Solutions using only Windows standard commands are more difficult because of the characters <, > and " in the XML file which have a special meaning on command line.

当然重要的是要知道执行批处理文件时文件中的当前端口号未知.从最初的问题来看,这对我来说还不是很清楚.这使它变得更加困难.

It is of course an important fact to know that the current port number in file is not known on executing the batch file. That was not really clear for me from the initial question. This makes it more difficult.

一种解决方案是先搜索现有的端口值,找到后进行替换.

One solution would be to first search for existing port value and once found do the replace.

@echo off

rem Search in file for a line where first opening tag is
rem "Connector" which has as first attribute "port" and
rem one more attribute "protocol" and assign the value
rem of the attribute port to an environment variable.

for /F "tokens=1-4 delims==<     " %%A in (Test.xml) do (
    if "%%A"=="Connector" (
        if "%%B"=="port" (
            if "%%D"=="protocol" (
                set "PortNumber=%%~C"
                goto Replace
            )
        )
    )
)
echo Could not find the port value of interest.
goto :EOF

:Replace
xchang32.exe Test.xml "port=^34,%PortNumber%^34 protocol" "port=^34,%~1^34 protocol"
set "PortNumber="

注意:

delims=之后,在命令 for 处有4个字符:

There are 4 characters after delims= on line with command for:

  1. 等号
  2. 左尖括号,
  3. 水平制表符(浏览器显示时不是空格序列)
  4. 一个空格字符.
  1. an equal sign,
  2. a left angle bracket,
  3. a horizontal tab character (not a sequence of spaces as browser displays) and
  4. a single space character.

分隔符的顺序很重要,否则命令行解释器会由于语法错误而退出批处理脚本.

The order of the delimiter characters is important as otherwise command line interpreter would exit batch script because of a syntax error.

感兴趣的行被命令 for 划分为以下四个定界符:

The line of interest is split up by command for with those 4 delimiters into:

  • 令牌1:Connector
  • 令牌2:port
  • 令牌3:"third"
  • 令牌4:protocol
  • 还有更多不受欢迎的代币.
  • token 1: Connector
  • token 2: port
  • token 3: "third"
  • token 4: protocol
  • and more tokens not of interest.

将这4个标记分配给循环变量 A (标记名称), B (第一个属性的名称), C (值第一个属性的名称)和 D (第二个属性的名称.

Those 4 tokens are assigned to the loop variables A (tag name), B (name of first attribute), C (value of first attribute) and D (name of second attribute.

变量 A B D 的值用于检查是否找到了右行.通过肯定检查将变量 C 的值分配给环境变量,同时删除周围的双引号.然后,通过跳转退出循环以替换部分批处理脚本.

The values of variables A, B and D are used to check if the right line was found. The value of variable C is assigned on positive check to an environment variable with removing the surrounding double quotes. Then the loop is exited with a jump to replace part of the batch script.

免费工具 xchang32.exe 用于在文件中进行替换,而无需进行其他任何更改.由于分配给属性 port 的值是整数值,因此有必要在第一个^34之后使用逗号,以使工具知道引用双引号字符的整数在何处结束.

Again free tool xchang32.exe is used to make the replacement in the file without changing anything else. As the value assigned to attribute port is an integer value, it is necessary to use a comma after first ^34 to let the tool know where the integer number referencing the double quote character ends.

有关命令帮助,请在for /?help for的命令提示符窗口中执行.

For help on command for execute in a command prompt window either for /? or help for.

这篇关于如何在批处理脚本中查找字符串并将其替换为另一个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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