3

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 !

Quantum Sushi
  • 504
  • 7
  • 23
  • 2
    The simplest way to reproduce a text file without its first line, _as long as converting contained tabs to spaces isn't an issue,_ is: `@"%__AppDir__%more.com" +1 "test.txt" > "modifiedtest.txt"` – Compo Jun 29 '20 at 13:28
  • 3
    or `>RemoveFirstLine.txt – ScriptKidd Jun 29 '20 at 13:57
  • 1
    @HackingAddict1337: that's genius. You want that to convert into an answer? – Stephan Jun 29 '20 at 14:23
  • Thanks a lot to both of you HackingAddict1337 and Compo, I got my solution and you helped me ! Thanks again ! ^^ – Quantum Sushi Jul 01 '20 at 08:52

2 Answers2

3

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.

ScriptKidd
  • 803
  • 1
  • 5
  • 19
2

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%"
Stephan
  • 53,940
  • 10
  • 58
  • 91