在文本文件中查找和替换字符串

时间:2016-09-15 14:14:25

标签: windows batch-file cmd

我必须使用Windows命令/批处理脚本替换文本文件(InputFile.txt)中的字符串。我找到了以下脚本(replace.cmd),但它没有给我准确的结果。

InputFile.txt

1111 aaaa
2222 bbbb
$cc = 3333

我用来将replace.cmd替换为$cc = 3333的批处理脚本(cc = 4444)是:

@echo OFF 
setlocal enabledelayedexpansion

set "search=$cc = 3333"
set "replace=cc = 4444"
set "textfile=InputFile.txt"
set "newfile=OutputFile.txt"
(for /f "delims=" %%i in (%textfile%) do (
    set "line=%%i"
    setlocal enabledelayedexpansion
    set "line=!line:%search%=%replace%!"
    echo(!line!
    endlocal
))>"%newfile%"

运行代码后我得到的输出是:

1111 aaaa
2222 bbbb
3333=cc = 4444= 3333

应该是这样的:

1111 aaaa
2222 bbbb
cc = 4444

3 个答案:

答案 0 :(得分:1)

如果你想要一个像这样的vbscript的小技巧:

ng-class="{'blackout': $index==$rowIndex}"

编辑:2016年9月15日@ 19:30

@echo off
set "Data=some data .... $cc = 3333"
echo The data before replacing is "%Data%" & pause
set "String1=$cc = 3333"
set "String2=cc = 4444" 
Call :ReplaceString "%Data%" "%String1%" "%String2%"
echo The data after replacing is "%Data%" & pause & exit
::*************************************************************************************
:ReplaceString <Data> <String1> <String2>
(
    echo Wscript.echo Replace("%~1","%~2","%~3"^)
)>"%tmp%\%~n0.vbs"
for /f "delims=" %%a in ('Cscript /nologo "%tmp%\%~n0.vbs"') do ( set "Data=%%a" )
If Exist "%tmp%\%~n0.vbs" Del "%tmp%\%~n0.vbs"
exit /b
::*************************************************************************************

答案 1 :(得分:0)

我们需要一位专家!当然,他/她知道如何做到这一点。

替换包含=符号的字符串很棘手。据我所知,你必须分成两个并测试这两个术语,或者如果要修复的字符串是固定的,请尝试

@echo off

set "search=$cc = 3333"
set "replace=cc = 4444"
set "textfile=InputFile.txt"
set "newfile=OutputFile.txt"

>"%newfile%" (
  for /f "delims=" %%i in (%textfile%) do (
    if "%%i" equ "%search%" (
      echo(%replace%
    ) else (
      echo(%%i
    )       
  )
)
exit/B

答案 2 :(得分:0)

只需更改你的for循环:

@echo off

set "search=$cc = 3333"
set "replace=cc = 4444"
set "textfile=InputFile.txt"
set "newfile=OutputFile.txt"

>"%newfile%" (for /f "delims=" %%i in (%textfile%) do (
        If /I "%%i" Equ "%search%" (Echo=%replace%) Else (Echo=%%i)))
exit/B