Baff
Baff

Reputation: 47

Batch File: delete lines in a bunch of txt files

i've got a problem with saving txt files in a loop i made to delete the first three rows of the txt files. My code so far is the following:

@echo off

setlocal enableextensions enabledelayedexpansion
set /a count=1
for %%a in ("C:\Users\%Username%\Desktop\conduct\*.txt") do (
echo %%a
Copy NUL C:\Users\%Username%\Desktop\conducterei\conduct!count!.txt
    for /f "skip=3 tokens=*" %%g in (%%a) do (
    >>"C:\Users\%Username%\Desktop\conducterei\conduct!count!.txt" echo %%g
    )
set /a "count+=1"
)

pause

I read that the For /f loop does not accept wildcards so i did a nested loop but now i have the problem with copying the text saved in the %%g variable. DOS prompts that my destination folder does not exist, but i just created it with COPY NUL in the first for loop.

The command in the second for-loop seems not correct to save %%g in a text file. The original text file looks like that:

blabla
blank
blank
4 5 6 7 8 9 2143
1 2 6 7 1 0 9763
. . . . . . .

I only want the numbers in my new text files! I already read in this thread (Batch File To Copy Every Line In .txt File And Then Create New .txt File For Each Line) about the problem, but only for one txt file i need to do it for a lot ;)

I hope my question is clear :)

Greetz Baff

Upvotes: 1

Views: 983

Answers (1)

dbenham
dbenham

Reputation: 130849

"DOS prompts that my destination folder does not exist, but i just created it with COPY NUL in the first for loop."

No, you attempted to create a file, not a folder. And based on your reported error message, that attempt failed because the path you provided does not exist. I suspect a typing error - look carefully at the path you use in both the COPY and ECHO lines, and verify it actually exists. If it doesn't, then use MD or MKDIR to create it.

Note - you do not need to create an empty file before you append to it. >> will create the file if it does not exist already.

There is a simpler and much faster way to copy a file, skipping N lines, using MORE.

@echo off
setlocal enableDelayedExpansion
set /a count=1
for %%a in ("C:\Users\%Username%\Desktop\conduct\*.txt") do (
  echo %%a         
  more +3 "%%a" >"someOtherPathThatExists\conduct!count!.txt"
  set /a count+=1
)
pause

This technique has the following limitations:

  • <TAB> characters are converted into a string of spaces
  • MORE fails (hangs) if there are more than 64k lines in the file

Upvotes: 2

Related Questions