Problem with search and replace batch file

前端 未结 3 374
慢半拍i
慢半拍i 2021-01-15 11:58

I have an XML file and I have a batch file to search for a specific string within that file, replace it with a string defined by the user and then output it to a new XML fil

相关标签:
3条回答
  • 2021-01-15 12:31

    check out my answered question about the exact same topic, it was answered perfectly.

    how to replace a string on the second line in a text file using a batch file?

    hope this helps!

    0 讨论(0)
  • 2021-01-15 12:36

    You need to create the empty file entities_1.xml, because for some obscure reason >> won't create it with cmd as shell.
    So use TYPE NUL > entities_1.xml just before your FOR loop, to create a zero-byte long file.

    0 讨论(0)
  • 2021-01-15 12:37

    It's the wrong way of receiving a line by set str=%%G while the delayed expansion is enabled.
    It's because the delayed expansion phase is after the %%v expansion phase.

    With disabled delayed expansion you got the problem, that you can not replace the string in a safe way. So you have to toggle the delayed expansion.

    @echo off > entities_1.xml
    setLocal DisableDelayedExpansion
    
    if exist entities_1.xml del entities_1.xml
    set /p name= What is the new space NAME?
    
    for /f "tokens=* delims= " %%G in (entities.xml) do (
        set str=%%G
        setLocal EnableDelayedExpansion
        set str=!str:[Test Space]=[%name%]!
        >> entities_1.xml echo(!str!
        endlocal
    )
    

    Switching the redirection, so you didn't append always a space.
    Using echo(, so you get not echo is on if the !str! is empty.

    0 讨论(0)
提交回复
热议问题