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

Find a line in a file and replace the next line

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

@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

你需要在开头设置三个变量 yourself.Have 记住更多的命令设置空格而不是制表符

@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 行之前。

尽管我喜欢使用批处理,但我通常会避免使用纯原生批处理来编辑文本文件,因为强大的解决方案通常既复杂又缓慢。

这可以使用 JREPL.BAT - 一个执行正则表达式替换的混合 JScript/batch 实用程序轻松高效地完成。 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为false时才会替换下一行。

搜索字符串匹配整行。

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

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

@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.