Remove the last line from the text file (including empty lines) using batch

喜夏-厌秋 提交于 2021-01-27 18:46:00

问题


My text file

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
)

回答1:


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

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).

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




回答2:


What about a simple:

FINDSTR /R /I /V "^$ Footer" file.txt>>newfile.txt

?

  1. /R means regexp
  2. /I means case insensitive
  3. /V means EXCLUDE matches, instead of showing

in the double quotes are (separated by space) all the regexps that will be applied:

  1. ^$ matches empty lines
  2. Footer matches the exact word Footer



回答3:


pretty straight forward: read until you hit the footer, then quit (removes the Footer and anything after):

@echo off
for /F "delims=" %%j in (file.txt) do (
  echo %%j|findstr /b "Footer" >nul && goto :done
  echo %%j>> newfile.txt
)
:done


来源:https://stackoverflow.com/questions/49557931/remove-the-last-line-from-the-text-file-including-empty-lines-using-batch

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!