如何替换文本文件的最后20行中的文本?

时间:2014-05-20 15:10:26

标签: batch-file

@ECHO OFF & SETLOCAL
copy /Y C:\LOG.DIR LOG.DIR
set "old=INACTIVE"
set "new=ACTIVE"
FOR /f %%a IN ('^<log.DIR find /v /c ""') DO SET /a length=%%a
SET /a length-=20
SETLOCAL ENABLEDELAYEDEXPANSION
<log.DIR  (
FOR /l %%a IN (1,1,%length%) DO (
    SET "line="
    SET /p "line="
    ECHO !line!
))>newfile
ENDLOCAL
for /f "skip=%length% delims=" %%a in (LOG.DIR) do (
    set "str=%%a"
    SETLOCAL ENABLEDELAYEDEXPANSION
    set "str=!str:%old%=%new%!"
    >>newfile ECHO !str!
    endlocal
)

我只想将 INACTIVE 的最后20行更改为 ACTIVE 。如果文件少于20行,则应更改所有文件行。

但是,如果文件中的行数小于20,则当前新文件为空。

要避免空新文件需要更改哪些内容?

1 个答案:

答案 0 :(得分:0)

@echo off 
    setlocal enableextensions enabledelayedexpansion

    copy /y c:\log.dir log.dir

    set "old=INACTIVE"
    set "new=ACTIVE"

    for /f %%a in ('^<log.dir find /v /c ""') do set /a "length=%%a"

    if %length% gtr 20 ( set /a "startPoint=length-20+1" ) else ( set "startPoint=1" )

    <log.dir (
        for /l %%a in (1,1,%length%) do (
            set "line="
            set /p "line="
            if not defined line (
                echo(
            ) else if %%a lss %startPoint% (
                echo(!line!
            ) else (
                echo(!line:%old%=%new%!
            )
        )
    )>newfile

    endlocal

根据文件长度调整从哪里开始。如果您有超过20行,则计算起点。如果您的线路较少,请从头开始处理。