string 读取文件并用新字符串替换字符串的批处理文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15291341/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
A Batch file to read a file and replace a string with a new one
提问by Joyel
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. Seems like str variable holds no value at all when assigned to %%i. Can someone help me?
这会导致新文件的“Echo is off”与 myfile 中的行数一样多。似乎 str 变量在分配给 %%i 时根本没有任何值。有人能帮我吗?
回答by BDM
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. To combat this, you can use setlocal enabledelayedexpansion
, and replace the percent signs (%
) with an exclamation mark (!
):
这是因为在for
循环中,变量在循环完成之前不会更新。为了解决这个问题,您可以使用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.
顺便说一下,这个片段是假设oldstring
并且newstring
不会在 forloop 中设置,否则事情会变得一团糟。
Have fun.
玩得开心。
回答by dave
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
回答by oobe
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
工作完美,并没有删除行文件开头的空格