-1

I have text file , I want to delete last line only without erase spaces I try this code : delete last line with all spaces

@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

I want delete only last line no more . thank you

SKIKDA
  • 13
  • 4
  • Following the rules of SO usage https://stackoverflow.com/help , please tell in what way your code is not working as you wish. Also, the `FOR /F` loop specifies `usebackq`, but there are no GRAVE ACCENT characters. – lit Oct 26 '21 at 17:03
  • @lit, the `for` loop includes the `UseBackQ` option, for a reason, please read the help information for the command if you want to know why. – Compo Oct 26 '21 at 17:11

1 Answers1

1

Please read my answer on How to read and print contents of text file line by line?

Then the code of the batch file should be clear which is working for all ANSI, OEM and UTF-8 encoded text files with lines with line number and colon prepended on each line by FINDSTR not longer than 8184 characters.

@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "SourceFile=%~1"
if not defined SourceFile set "SourceFile=file.txt"
if not exist "%SourceFile%" echo ERROR: File "%SourceFile%" not found!& exit /B 1

set "Line="
for /F delims^=^ eol^= %%I in ('%SystemRoot%\System32\findstr.exe /N "^" "%SourceFile%" 2^>nul') do (
    setlocal EnableDelayedExpansion
    if defined Line (echo(!Line:*:=!>>"%SourceFile%") else del "%SourceFile%"
    endlocal
    set "Line=%%I"
)
if exist "%SourceFile%" for %%I in ("%SourceFile%") do if %%~zI == 0 del "%SourceFile%"
endlocal

The source file of which name is passed to the batch file with the first argument string or as specified in the batch file is deleted if it contains just one line.

The source file is also deleted if it is an empty file, i.e. is a file with a file size equal 0. That is done by the last but one line of the batch file.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

  • call /? ... explains %~1 ... first argument with surrounding " removed.
  • del /?
  • echo /?
  • endlocal /?
  • exit /?
  • findstr /?
  • for /?
  • if /?
  • set /?
  • setlocal /?

See also single line with multiple commands using Windows batch file for an explanation of the operator & as used on fifth line.

Mofi
  • 46,139
  • 17
  • 80
  • 143