Problem with deleting a line

March 11, 2011 at 16:29:48
Specs: Windows XP, AMD Athlon 5400+ // 3GB RAM
Hi again. :)

I have this code that deletes a line from a file (in this case line 4):

@echo off > file2.txt & setLocal enableDELAYedeXpansion

set N=
for /f "tokens=* delims= " %%a in (file.txt) do (
set /a N+=1
if !N! neq 4 >> file2.txt echo.%%a

del file.txt
rename file2.txt file.txt

But the problem is it also deletes all of the blank lines in the file. How can I make it only delete the 4th line?

See More: Problem with deleting a line

Report •

March 11, 2011 at 20:40:27
Do you want to delete the fourth line with text on it as above, but still keep the blank lines in the output?

Alternatively do you want the actual fourth line(including blanks) removed with the rest of the lines output as is?

The script above will also play havoc with exclamation marks.

Report •

March 12, 2011 at 03:33:20
Thanks for you reply.
Yes, I want to delete the forth line of the file (with text on it) it and keep the blank lines.

I do have exclamation marks in my file but I don't think they are making any problems.

Report •

March 12, 2011 at 05:59:20
So the exclamation marks don't disappear/expand variables with the other script? hmm......

Well anyway this works for me on xp, just be aware it doesn't treat lines with only spaces or tabs as empty. I also added some file validation....

@echo off
SetLocal DisableDelayedExpansion

set in_file="file.txt"
set out_file="outfile.txt"

> con echo:
> con echo ^>^>^>^> Creating  temp file (%out_file%)
> con 2>&1 copy /-y nul %out_file%
for %%a in (%out_file%) do if not %%~za==0 (
    > con echo:
    > con echo ^>^>^>^> %out_file% exists and wasn't overwritten
    > con echo ^>^>^>^> No changes made, exiting...
    exit /b

set cnt=1

for /f "delims=" %%a in ('find /n /v "" ^< %in_file% ') do (
    set line=%%a
    SetLocal EnableDelayedExpansion
    set line=!line:*]=!
    if defined line (
        if !cnt! neq 4 (
            >> !out_file! echo !line!
        set /a cnt+=1
    ) else (
        >> !out_file! echo:


> con echo:
> con echo ^>^>^>^> If you choose "no" %in_file% remains unchanged
> con echo ^>^>^>^> %out_file% will remain and contain the modification
move /-y %out_file% %in_file%

Report •
Related Solutions

Ask Question