Delete line of a text file with batch

Viewed 572

I saw that in batch, to delete a specific line from a text file, you need to do it with findstrthat allow you to find your line and then delete it. But is there a way to do it when you don't know the line ? I got another program that fills the file and the batch must delete the first line. Does anyone know how to do it ?

I tried with something thet reads a line from an index and then use what I got with findstr, but it doesn't work:

@echo off
setlocal EnableDelayedExpansion
set count=1
for /f "tokens=*" %%a in (test.txt) do (
if !count! equ 1 (set "TIMER=%%a")
if !count! equ 1 (type test.txt | findstr /v %TIMER%)
set /a count+=1
)
echo %TIMER%
timeout %TIMER%
for /f "tokens=*" %%a in (test.txt) do (
echo %%a
)
pause

It tells me : FINDSTR : wrong command line (the piece of code for the loop on the lines of the file and find a specific line was found on the internet)

So where is the problem ? Or maybe does someone know something like delete(x) and it deletes the line ? Just something that takes an INDEX... ^^'

(The last for loop is used to check if the line was removed btw)

Thanks by advance for any help !

2 Answers

To remove the first n lines from a file without converting tabs into spaces:

@echo off
>RemoveFirstLine.txt <test.txt (
    FOR /L %%N in (1 1 1) do set/p"=" SKIP N lines
    %__APPDIR__%findstr.exe /R "^"
)

This works as FINDSTR moves the pointer from STDIN, while FIND and MORE do not.

Your code mainly doesn't work because the lack of delayed expansion.

But there are easier ways to achieve your goal. If Compo's suggestion (more.com" +1 "test.txt" > "modifiedtest.txt") doesn't work for you (need to keep TABs or need to remove another line than the first one), the following might work for you:

@echo off
setlocal
set file=test.txt
set lineToDelete=1
(for /f "tokens=1* delims=:" %%a in ('findstr /N "^" "%file%" ^|findstr /bv "%lineToDelete%:"') do echo/%%b) > "%file%.tmp
move /y "%file.tmp%" "%file%"
Related