Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch Delete a line in a text file?

I'm pulling my hair out finding a simple example of a DOS batch file that will delete the first line of several thousand txt files and save the file with the original file name. Following a batch process performed by another program, I then have to ADD the deleted line ( a text string consisting of "X,Y,Z") at the beginning of each file following the external processing.

like image 871
Tom Colson Avatar asked Mar 27 '11 17:03

Tom Colson


1 Answers

You can use more +1 to skip the first line of the file. Then you can pipe it into a temporary one (you cannot edit text files in place):

for %x in (*.txt) do (more +1 "%x">tmp & move /y tmp "%x")

After that you can use a similar technique to re-add the first line:

for %x in (*.txt) do ((echo X,Y,Z& type "%x")>tmp & move /y tmp "%x")

If you use those in a batch file, remember to double the % signs:

@echo off
for %%x in (*.txt) do (
    more +1 "%%x" >tmp
    move /y tmp "%%x"
)
rem Run your utility here
for %%x in (*.txt) do (
    echo X,Y,Z>tmp
    type "%%x" >>tmp
    move /y tmp "%%x"
)

Ok, apparently more doesn't work with too large files, which surprises me. As an alternative, which should work if your file does not contain blank lines (though it looks like CSV from what I gathered):

for %%x in (*.txt) do (
    for /f "skip=1 delims=" %%l in ("%%x") do (>>tmp echo.%%l)
    move /y tmp "%%x"
)
like image 180
Joey Avatar answered Sep 26 '22 15:09

Joey