我正在尝试创建一个蝙蝠文件,我可以将一个参数传递给该文件,该文件将被写入文件中特定位置的文本文件。文件的位置从一开始就是未知的,但是可以使用硬编码的值找到。
文本文件的结构:
SECTION1
value1 = 123456
value2 = asdf
value3 = 1111
SECTION2
value1 = 654321
value2 = something
value3 = 875
SECTION3
value1 = 92948
value2 = aaaaaaa
value3 = 6499
目标是以这种方式调用批处理文件:
batch.bat somethingelse
...,然后将其准确更新,只有第2节(值2)从“某物”更新为“某物”。就像我写的一样,我非常高兴在批处理文件中对“ SECTION2”和“ value2”进行硬编码。
这是我到目前为止所拥有的。不多我的处理方法分为三个步骤,但也许这是错误的处理方式:
1:确定SECTION2的起始位置:
for /f "delims=:" %%N in ('findstr /n "SECTION2" "file.txt"') do set section=%%N
echo %section%
2:从%section%的开头查找value2的第一个匹配项并存储该行号:
Not sure how to accomplish this.
3:在最后一行,用“ value2 =” +开头(即第一个参数)覆盖它:
This gives me what the row should look like, but I'm not sure how to actually write it.
set output=value2 = %1
echo %output%
答案 0 :(得分:1)
使用脚本语言使用PowerShell等功能齐全的正则表达式要容易得多,因为自版本7起,它们是Windows的一部分(-raw参数需要PSv3 +)。
要成为话题,该PowerShell一衬里将成批包装:
powershell -NoP -C "(gc .\file.txt -raw) -replace '(?SM)(?<=SECTION2.*?value2 = ).*?$(?=.*?^[^=]+$)','somethingelse'|Set-Content .\file.txt"
正则表达式使用{正)lookarounds仅在SECTION2 / 3之间匹配value2
示例输出:
SECTION1
value1 = 123456
value2 = asdf
value3 = 1111
SECTION2
value1 = 654321
value2 = somethingelse
value3 = 875
SECTION3
value1 = 92948
value2 = aaaaaaa
value3 = 6499
答案 1 :(得分:0)
有几种通过批处理文件解决此问题的方法。这使用完全相同的逻辑,非常简单:
@echo off
setlocal
rem 1: Identify where SECTION2 starts:
for /f "delims=:" %%N in ('findstr /n "SECTION2" "file.txt"') do set "section=%%N"
rem 2: From the start of %section% find the first occurrence of value2 and store that row number:
set "firstRow="
for /f "delims=:" %%N in ('findstr /n "value2" "file.txt"') do (
if %%N gtr %section% if not defined firstRow set "firstRow=%%N"
)
rem 3: At the final row number, overwrite it with "value2 = " + somethingelse, i.e. the first parameter:
(for /F "tokens=1* delims=:" %%N in ('findstr /n "^" "file.txt"') do (
if %%N neq %firstRow% (
echo %%O
) else (
echo value2 = %1
)
)) > newFile.txt
rem Final step: update the new file
move /Y newFile.txt file.txt