我想从顶部和底部修剪文本文件。 假设文本文件包含90行。我想删除前x行和下y行并更新文件。 (即只留下范围x + 1到y-1。 因此,我打算编写批处理文件并按如下方式运行。
trimmer.bat file1.txt 2 8
以下此代码有以下限制 (a)文件开放/修改两次 (b)修剪范围内的空白行(我不想删除这些行)
请帮我纠正
@echo off
rem %1% file name %2%range begins %3%range ends
rem Step1: this code trims the bottom section
set /a bot_trim=%3
echo Removing...
for /f "skip=%bot_trim% delims=*" %%a in (%1) do (
echo %%a >>newfile.txt
) >nul
echo Lines removed, rebuilding file...
xcopy newfile.txt %1 /y >nul
echo File rebuilt, removing temporary files
del newfile.txt /f /q >nul
echo file bottom trimmed...
rem Step2: this code trims the Top section
set /a Top_trim=%2-1
echo Removing...
for /f "skip=%Top_trim% delims=*" %%a in (%1) do (
echo %%a >>newfile.txt
) >nul
echo Lines removed, rebuilding file...
xcopy newfile.txt %1 /y >nul
echo File rebuilt, removing temporary files
del newfile.txt /f /q >nul
echo file bottom trimmed...
echo file trim completed !!
pause
file1.txt的内容
aa
ff
ff
dd
dd
ee
ee
ee
答案 0 :(得分:0)
@ECHO OFF
SETLOCAL
FOR /f "tokens=1-3 delims=:" %%a IN ('FIND /c /v "" %1') DO IF "%%c"=="" (SET /a endline=%%b-%3) ELSE (SET /a endline=%%c-%3)
ECHO %2 %endline%
(
FOR /f "tokens=1*delims=:" %%a IN ('findstr /n /r "^" %1') DO (
IF %%a gtr %endline% GOTO done
IF %%a gtr %2 ECHO(%%b
)
)>newfile.txt
:done
GOTO :EOF
旨在满足您的原始规格。不试图满足文件/目录名中的空格和批次重要符号,但如果需要,可以使用目录名。
以:
开头的行会被损坏。
制作newfile.txt