在文件中查找一行并替换下一行

时间:2015-02-17 17:10:04

标签: windows batch-file replace

使用.bat脚本,我想找到一行# Site 1,并用变量替换下一行中的文本。我在StackOverflow上找到了用于查找和替换行的教程,但没有找到一行并替换下一行。有什么帮助吗?

4 个答案:

答案 0 :(得分:3)

@echo off

set "the_file=C:\someFile"
set "search_for=somestring"
set "variable=http://site1"

for /f "tokens=1 delims=:" %%# in ('findstr /n  /c:"%search_for%" "%the_file%"') do (
    set "line=%%#"
    goto :break
)
:break


set /a lineBefore=line-1
set /a nextLine=line+1


break>"%temp%\empty"&&fc "%temp%\empty" "%the_file%" /lb  %lineBefore% /t |more +4 | findstr /B /E /V "*****" >newFile
echo %variable%>>newFile
more "%the_file%" +%nextLine% 1>>newFile

echo move /y newFile "%the_file%"

检查newFile是否正常,然后移除最后一行前面的echo

你需要自己设置三个变量。请记住,更多的命令设置空格而不是标签

答案 1 :(得分:0)

@ECHO OFF
SETLOCAL
SET "filename=q28567045.txt"
SET "afterme=# Site 1"
SET "putme=put this line after # Site 1"
SET "skip1="
(
FOR /f "usebackqdelims=" %%a IN ("%filename%") DO (
 IF DEFINED skip1 (ECHO(%putme%) ELSE (ECHO(%%a)
 SET "skip1="
 IF /i "%%a"=="%afterme%" SET skip1=y
)
)>newfile.txt

GOTO :EOF

制作newfile.txt

首先重置跳过该行的标志`skip1,然后逐行读取该文件。

如果设置了skip1标志,则替换行为echo以代替读取的行;如果没有,读取的行就会被回显。

然后清除skip1标志

如果读取到%%a的行与分配给afterme的字符串相匹配,则会设置标记skip1(到y - 但是值是什么值无关紧要是)

请注意,空行和那些以;开头的行将被忽略而不会被重现 - 这是for /f的标准行为。

如果要重新启动起始文件,只需添加

即可
move /y newfile.txt "%filename%" 

goto :eof行之前。

答案 2 :(得分:0)

即使我喜欢使用批处理,我通常也会避免使用纯本机批处理来编辑文本文件,因为强大的解决方案通常很复杂且很慢。

使用JREPL.BAT - 一种执行正则表达式替换的混合JScript /批处理实用程序,可以轻松高效地完成此操作。 JREPL.BAT是纯脚本,可​​以在任何Windows机器上从XP开始本地运行。

@echo off
setlocal
set "newVal=Replacement value"
call jrepl "^.*" "%newValue%" /jbeg "skip=true" /jendln "skip=($txt!='# Site 1')" /f test.txt /o -

/ F选项指定要处理的文件

值为-的/ O选项指定用结果替换原始文件。

/ JBEG选项初始化命令以跳过(不替换)每一行。

/ JENDLN选项在写出之前检查每一行的值,如果匹配# Site 1则设置SKIP关闭(false)。只有当SKIP为假时,才会替换下一行。

搜索字符串匹配整行。

替换字符串是存储在变量中的值。

答案 3 :(得分:0)

此问题与this one类似,可能使用等效的解决方案。下面的纯批处理文件解决方案应该是同类中最快的。

@echo off
setlocal EnableDelayedExpansion

set "search=# Site 1"
set "nextLine=Text that replaces next line"


rem Get the line number of the search line
for /F "delims=:" %%a in ('findstr /N /C:"%search%" input.txt') do set /A "numLines=%%a-1"

rem Open a code block to read-input-file/create-output-file

< input.txt (

   rem Read the first line
   set /P "line="

   rem Copy numLines-1 lines
   for /L %%i in (1,1,%numLines%) do set /P "line=!line!" & echo/

   rem Replace the next line
   echo %nextLine%

   rem Copy the rest of lines
   findstr "^"

) > output.txt

rem Replace input file with created output file
move /Y output.txt input.txt > NUL

如果输入文件有空行并且还有其他限制,则此方法将失败。 有关此方法的进一步说明,请参阅this post

相关问题