在迭代文本文件上运行批处理命令
问题描述:
我有一组文本文件(log0.txt,log1.txt等),我想将其转换为其他格式。但是,每个文件的最后一行是不完整的,所以我想写一个批处理命令,它将删除每个文件的最后一行。在迭代文本文件上运行批处理命令
将军命令我工作是这样的:
@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
rem Count the lines in file
set /a count=-1
for /F %%a in (log0.txt) DO set /a count=!count!+1
rem Create empty temp file
copy /y NUL temp.txt >NUL
rem Copy all but last line
for /F %%a in (log0.txt) DO (
IF /I !count! GTR 0 (
echo %%a >>temp.txt
set /a count=!count!-1
)
)
rem overwrite original file, delete temp file
copy /y temp.txt log0.txt >NUL
del temp.txt
rem This for testing
type log0.txt
而不必复制并粘贴此为每个文本文件的,是那里的批处理命令对所有我的文字的操作方式文件?
答
最后一行的排除可以用更简单的方式实现。我修改了你的代码并添加了所有文本文件的处理。
@echo off
setlocal EnableDelayedExpansion
rem Process all text files
for %%f in (*.txt) do (
echo Processing: %%f
rem Copy all but last line in temp.txt file
set "line="
(for /F %%a in (%%f) do (
if defined line echo !line!
set "line=%%a"
)) > temp.txt
rem Overwrite original file
move /Y temp.txt %%f >NUL
rem This for testing
type %%f
)
答
将代码重建为函数。
@echo off
for %%F in (*.txt) do (
call :removeLastLine "%%~F"
)
exit /b
:removeLastLine
SETLOCAL ENABLEDELAYEDEXPANSION
set "filename=%~1"
echo Processing '!filename!'
rem Count the lines in file
set /a count=-1
for /F %%a in (!filename!) DO set /a count+=1
rem Copy all but last line
(
for /F %%a in (!filename!) DO (
IF /I !count! GTR 0 (
echo(%%a
set /a count=!count!-1
)
)
) > temp.txt
rem overwrite original file, delete temp file
copy /y temp.txt !filename! >NUL
del temp.txt
rem This for testing
type !filename!
endlocal
exit /b
答
使用powershell脚本可能会比你的方法更快。把下面的脚本到一个文件名为allbutlast.ps1:
$content = Get-Content $args[0]
$lines = $content | Measure-Object
$content | select -First ($lines.count-1)
然后从您的批处理文件调用此:
powershell -file allbutlast.ps1 log0.txt>temp.txt
copy /y temp.txt log0.txt >NUL
del temp.txt
你的循环中的想法非常好 – jeb
@jeb:谢谢jeb! '':-) – Aacini