使用批处理从文本文件中删除最后一行(包括空行) [英] Remove the last line from the text file (including empty lines) using batch

查看:257
本文介绍了使用批处理从文本文件中删除最后一行(包括空行)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的文本文件

Header
A,B,C,D,E
F,G,H,I,J
K,L,M,N,O
Footer

我要删除页脚以及页脚下方的空行(空行不是静态的)和我的预期输出

I want remove the Footer and also empty lines below Footer (Empty lines are not static) And my expected output

Header
A,B,C,D,E
F,G,H,I,J
K,L,M,N,O

我尝试了以下代码,但是它仅删除了最后一个空行.

I tried the below code, But it removing the last empty line alone.

set row=
for /F "delims=" %%j in (file.txt) do (
  if  defined row echo.!row!>> newfile.txt
  set row=%%j
)

推荐答案

这将是执行任务的通用方法;如果您希望有所不同,请考虑提供更多具体信息和示例文件:

This would be a generic way to perform the task; If you want something different consider providing more specific information and example file(s):

@Echo Off
SetLocal DisableDelayedExpansion

Set "SrcFile=file.txt"

If Not Exist "%SrcFile%" Exit /B
Copy /Y "%SrcFile%" "%SrcFile%.bak">Nul 2>&1||Exit /B

(   Set "Line="
    For /F "UseBackQ Delims=" %%A In ("%SrcFile%.bak") Do (
        SetLocal EnableDelayedExpansion
        If Defined Line Echo !Line!
        EndLocal
        Set "Line=%%A"))>"%SrcFile%"
EndLocal
Exit /B

您应在 4 行上更改文件名,以匹配实际源文件的名称.如果您对结果满意,可以选择删除 .bak 文件(这是原始文件的备份,为安全起见保存).

You should change your filename on line 4 to match your actual source file's name. If you are happy with the result you can optionally delete the .bak file, (which is a backup of the original file, saved for safety).

注意::生成的文件将以正常的 CRLF 结尾(即,底部会有空白行).

Note: The resultant file will end with the normal CRLF, (i.e there will be a blank line at the bottom).

这篇关于使用批处理从文本文件中删除最后一行(包括空行)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆