简体   繁体   English

批处理文件,用于读取文件并用新的替换字符串

[英]A Batch file to read a file and replace a string with a new one

I want to create a batch file to read every line of a file in a loop and replace a string with another one. 我想创建一个批处理文件,以在循环中读取文件的每一行,并用另一个替换字符串。 Following is my code snippet: 以下是我的代码段:

for /F "tokens=*" %%i in (myfile) do (
  set str=%%i
  set str=%str: %oldstring% = %newstring%%
echo %str% >> newfile
)

This results in a newfile with 'Echo is off' as many lines as there are in myfile. 这将导致一个新文件,其中“ Echo is off”与myfile中的行数一样多。 Seems like str variable holds no value at all when assigned to %%i. 好像str变量分配给%% i时根本没有任何值。 Can someone help me? 有人能帮我吗?

Try out this small script: 试试这个小脚本:

@echo off
set val=50
echo %val%
for /l %%i in (1,1,1) do (
    set val=%%i
    echo %val%
)
echo %val%
pause>nul

The output is: 输出为:

50
50
1

Not what you expected, right? 不是您所期望的,对吗?

That's because in a for loop, variables aren't updated until the loop has finished. 这是因为在for循环中,直到循环完成才对变量进行更新。 To combat this, you can use setlocal enabledelayedexpansion , and replace the percent signs ( % ) with an exclamation mark ( ! ): 为了解决这个问题,您可以使用setlocal enabledelayedexpansion ,并将百分号( % )替换为感叹号( ! ):

@echo off
setlocal enabledelayedexpansion
set val=50
echo %val%
for /l %%i in (1,1,1,) do (
    set val=%%i
    echo !val!
)
echo %val%
pause>nul

The output: 输出:

50
1
1

The reason the str variable holds no value (during the for loop) is because it hasn't been set beforehand. str变量不包含任何值(在for循环期间)的原因是因为尚未事先设置。

So, with these quick modifications, your script will work... 因此,通过这些快速修改,您的脚本将可以工作...

setlocal enabledelayedexpansion
for /f "tokens=*" %%i in (myfile) do (
    set str=%%i
    set str=!str: %oldstring% = %newstring%!
    echo !str! >> newfile
)

By the way, this snippet is assuming that oldstring and newstring won't be set within the forloop, otherwise things will get messy. 顺便说一句,这个片断是假设oldstringnewstring不会在for循环中进行设置,否则事情会变得混乱。

Have fun. 玩得开心。

having spent some time at this I got the correct way: 花了一些时间我得到了正确的方法:

@echo off
setlocal enabledelayedexpansion

set oldstring=AF-07295
set /a count=1000

for %%f in (*.*) do (
  set /a count=!count!+1
  for /f "tokens=*" %%i in (%%f) do (
    set str=%%i

    call set str=%%str:!oldstring!=!count!%%
    echo !str! >> %%~nf.ordnew

  )
)

endlocal
setlocal ENABLEDELAYEDEXPANSION
set filein="c:\program files\test1.txt"
set fileout="c:\program files\test2.txt"
set old=@VERSION@
set new=2.0.3
for /f "tokens=* delims=¶" %%i in ( '"type %filein%"') do (
    set str=%%i
    set str=!str:%old%=%new%!
    echo !str! >> %fileout% 
)

working perfect and isn't removing white spaces at the begining of the lines file 工作完美,并且在lines文件开头没有删除空格

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM