问题
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
?
- /R means regexp
- /I means case insensitive
- /V means EXCLUDE matches, instead of showing
in the double quotes are (separated by space) all the regexps that will be applied:
- ^$ matches empty lines
- 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