2015-04-28 109 views
2

我有一组文本文件(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 

而不必复制并粘贴此为每个文本文件的,是那里的批处理命令对所有我的文字的操作方式文件?

回答

1

最后一行的排除可以用更简单的方式实现。我修改了你的代码并添加了所有文本文件的处理。

@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 

) 
+0

你的循环中的想法非常好 – jeb

+0

@jeb:谢谢jeb! '':-) – Aacini

0

将代码重建为函数。

@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 
+0

我试图复制所有的(无论是功能和来电线)成批处理文件并运行它 - 但它不起作用。我错过了什么? –

+0

该函数必须在for循环之后,我将编辑编辑我的帖子 – jeb

+0

美丽。谢谢! –

0

使用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