简体   繁体   中英

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.

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"
)

Here's my version.

@echo off

for /f "usebackq delims=" %%f in (`dir /b *.txt`) do (
    echo X, Y, Z>"tmp.txt"
    type "%%f" >> tmp.txt
    move tmp.txt "%%f"
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM