Regex 使for循环一次读取文本文件的两行
我有一组文件夹,每个文件夹中都有一个同名的txt文件。它们是路径Regex 使for循环一次读取文本文件的两行,regex,variables,batch-file,for-loop,replace,Regex,Variables,Batch File,For Loop,Replace,我有一组文件夹,每个文件夹中都有一个同名的txt文件。它们是路径 C:\Test\Salford_xxx\MenuSettings.txt C:\Test\Salford_xxx\MenuSettings.txt C:\Test\Salford_xxx\MenuSettings.txt 其中xxx是一个随机的3位数字。我希望使用一个名为input.txt的文本文件更改这些文件的第一行,该文件的路径和替换每个文件第一行的行。看起来像这样 C:\TEST\SALFORD_001\MENUSETTI
C:\Test\Salford_xxx\MenuSettings.txt
C:\Test\Salford_xxx\MenuSettings.txt
C:\Test\Salford_xxx\MenuSettings.txt
其中xxx是一个随机的3位数字。我希望使用一个名为input.txt的文本文件更改这些文件的第一行,该文件的路径和替换每个文件第一行的行。看起来像这样
C:\TEST\SALFORD_001\MENUSETTINGS.TXT
AppName: "This needs replacing 1"
C:\TEST\SALFORD_011\MENUSETTINGS.TXT
AppName: "This needs replacing 2"
C:\TEST\SALFORD_345\MENUSETTINGS.TXT
AppName: "This needs replacing 3"
C:\TEST\SALFORD_761\MENUSETTINGS.TXT
AppName: "This needs replacing 4"
C:\TEST\SALFORD_768\MENUSETTINGS.TXT
AppName: "This needs replacing 5"
C:\TEST\SALFORD_999\MENUSETTINGS.TXT
AppName: "This needs replacing 6"
我已经编写了一个for循环,它将路径和替换放在变量中,它可以工作:
for /F "delims=" %%a in ('findstr /R /I "Salford" Input.txt') do (set "FilePath=%%a" echo %FilePath%)
for /F "delims=" %%b in ('findstr /R /I "AppName" Input.txt') do (set "NewName=%%b" echo %NewName%)
AppName是一个始终位于第一行的单词,用于搜索。
下面是替换每个文件行的脚本
set "search=Appname"
set "replace=%NewName%"
set "newfile=NewOutput.txt"
(for /f "delims=" %%i in (%FilePath%) do (
set "line=%%i"
setlocal enabledelayedexpansion
set "line=!line:%search%=%replace%!"
echo(!line!
endlocal
))>"%newfile%"
move "%newfile%" "%FilePath%"
但是,循环将继续到Salford_999文件夹中的最后一项,并仅编辑该文件。我如何让它读取input.txt的前两行,进行替换,然后循环到下两行,依此类推
谢谢我不明白你的代码是如何使用你的规范的。例如,“将路径放入变量的For循环”将所有路径分配给同一个变量,因此当For结束时,该变量具有最后一个值。另外,我不明白在第二个for中的
findstr
中使用“AppName”字符串文字时,它从何处获取。最后,如果有一个文件在input.txt文件中没有对应的行,会发生什么
另一种方法是将input.txt文件处理为一系列奇偶行,然后处理奇偶行中描述的每个文件;这可能导致更简单的解决方案:
@echo off
setlocal EnableDelayedExpansion
rem Process odd and even lines from input.txt file:
set "FilePath="
for /F "delims=" %%a in (input.txt) do (
if not defined FilePath ( rem Odd line...
rem Assign each odd line to "FilePath" variable
set "FilePath=%%a"
) else ( rem Even line...
rem Process this file, if it exists
if exist "!FilePath!" (
rem Block to enclose output to new file
> newfile (
rem The first line in new file is this even line in input.txt file
echo %%a
rem Copy all lines from this file, excepting the first one
more +1 "!FilePath!"
)
move /Y newfile "!FilePath!"
)
set "FilePath="
)
)
我不确定您的问题是如何读取两行input.txt。我看不到任何代码可以确保您只尝试编辑MENUSETTINGS.txt。这似乎就是你的问题所在。input.txt文件中有MenuSettings.txt引用,这就是所需的全部吗?这是每个文件夹中唯一的文本文件。好的,让我澄清一下AppName方面的问题。旧的菜单设置文件有一行
AppName:“http://example1.com“
在它们中。因此,“search”变量在旧的MenuSettings.txt文件中查找AppName,并用input.txt.Ok中“Newname”变量的内容替换它。这意味着AppName:
string是常量,仅用于标识奇数行,对吗?你测试过我的代码吗?它将在*.txt文件的第一行中插入整行奇数,所以您必须删除AppName:
和奇数行中的引号。。。是否要我修改代码以便像现在这样处理奇数行?