【问题标题】:String replace in a file by using batch file. gettting error : < was unexpected at this time batcch file使用批处理文件替换文件中的字符串。获取错误:<此时批处理文件是意外的
【发布时间】:2015-07-31 09:24:03
【问题描述】:

谁能建议我如何使用脚本替换文件中的字符串?该字符串包含一些特殊字符(例如:> “ ” )。

我的 searchString 如下所述

launcher.properties" />

我的新字符串如下所述

launcher.properties" >     <Permission User="Everyone" GenericAll="yes" /> </File> 

当我使用下面的脚本时出现错误

@echo off &setlocal
set "search=launcher.properties" />"
set "replace=launcher.properties" > <Permission User="Everyone"    
GenericAll="yes" /> </File> "
echo replaceing hte string....2222
set "textfile=home.wxs"
set "newfile=home_t2.wxs"
(for /f "delims=" %%i in (%textfile%) do (
    set "line=%%i"
    setlocal enabledelayedexpansion
    set "line=!line:%search%=%replace%!"
    echo(!line!
    endlocal
))>"%newfile%"
del %textfile%
rename %newfile%  %textfile%

出现以下错误:

The system cannot find the path specified.
< was unexpected at this time.

请帮帮我。

【问题讨论】:

    标签: string file batch-file replace


    【解决方案1】:

    对于这样复杂的替换,我会使用更复杂的脚本。 您可以尝试replacer.bat(文件名前的e?用于评估unicode序列-在这种情况下是引号)

    call replacer.bat e?home.wxs "launcher.properties\u0022/>" "launcher.properties\u0022 > <Permission User=\u0022Everyone\u0022  GenericAll=\u0022yes\u0022/> </File>"
    

    它是一个 jscript/bat 混合体,应使用 .bat 扩展名保存(您可以在任何 Windows 系统上使用它,无需先决条件)。

    您还可以查看FindRepl 和JRepl,它们是更复杂的工具

    【讨论】:

    • 感谢您的建议。当我使用 replacer.bat 文件时,出现以下错误 replacer.bat(68, 3) ADODB.Stream: File could not be open.
    • @mallikgm是同目录下的home.wxs吗?一般这表示脚本找不到文件
    【解决方案2】:

    我认为错误是由(初始)set 命令和命令行解释器 (CLI) 解析双引号的方式引起的,因为值中有双引号。 CLI 通常使用第二个双引号来结束第一个双引号打开的部分,第四个关闭第三个,依此类推。对于每对找到的双引号 "" 之间的所有内容,特殊字符,如分隔符、重定向、管道(&amp;、&lt;&gt;、|)都不会被检测到,但它们在这些对之外被识别。
    假设您的输入文件中的双引号字符串之间没有上述特殊字符(例如,"Everyone" 或 "yes" 就像在 %replace% 字符串中一样),以下代码应该可以工作:

    @echo off & setlocal
    set "search=launcher.properties"" />"
    set "replace=launcher.properties"" > <Permission User=""Everyone""    GenericAll=""yes"" /> </File> "
    echo replacing hte string....2222
    set "textfile=home.wxs"
    set "newfile=home_t2.wxs"
    (for /F "delims=" %%I in (%textfile%) do (
        set "line=%%I"
        setlocal enabledelayedexpansion
        set "line=!line:"=""!"
        set "line=!line:%search%=%replace%!"
        set "line=!line:""="!"
        echo(!line!
        endlocal
    )) > "%newfile%"
    del /P "%textfile%"
    rename "%newfile%" "%textfile%"
    

    我在这里所做的是在您的search 和replace 值中以及在原始文件%textfile% 的每个读取行中给出两个连续的双引号,而不是每个双引号,并将它们替换为单个" 在搜索和替换操作之后。在用于变量扩展/替换的%% 或!! 之间,双引号似乎没有更多特殊含义。

    注意:要检查search 和replace 的最终值,您不能使用echo,因为您遇到了与上面描述的相同的问题。而是键入 set search 或 set replace 以显示相应的值。

    【讨论】:

    • 我在del 命令中添加了/P 开关以暂停脚本以供用户提示,因此您可以在删除之前检查输出文件%newfile% 的内容。
    猜你喜欢
    • 2011-02-15
    • 1970-01-01
    • 2014-05-30
    • 2014-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    相关资源
    最近更新 更多