我有一组文本文件(log0.txt,log1.txt等),我想将其转换为其他格式。但是,每个文件的最后一行都是不完整的,所以我想写一个Batch命令,它将删除每个文件的最后一行。
我上班的一般命令如下:
@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
批处理命令是否可以对我的所有文本文件进行操作,而无需为每个文本文件复制和粘贴此内容?
答案 0 :(得分:1)
可以以更简单的方式实现排除最后一行。我修改了你的代码并添加了所有文本文件的处理。
balderdashy/waterline-schema
答案 1 :(得分: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
答案 2 :(得分: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