windows 批量删除文本文件中的一行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5450921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 08:13:34  来源:igfitidea点击:

Batch Delete a line in a text file?

windowsbatch-filedos

提问by Tom Colson

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.

我正在寻找一个简单的 DOS 批处理文件示例,该示例将删除数千个 txt 文件的第一行并使用原始文件名保存该文件。在另一个程序执行批处理之后,我必须在外部处理之后的每个文件的开头添加已删除的行(由“X,Y,Z”组成的文本字符串)。

回答by Joey

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

您可以使用more +1跳过文件的第一行。然后,您可以将其通过管道传输到临时文件中(您不能就地编辑文本文件):

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 moredoesn'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):

好的,显然more不适用于太大的文件,这让我感到惊讶。作为替代方案,如果您的文件不包含空行,它应该可以工作(尽管从我收集的内容来看它看起来像 CSV):

for %%x in (*.txt) do (
    for /f "skip=1 delims=" %%l in ("%%x") do (>>tmp echo.%%l)
    move /y tmp "%%x"
)

回答by adarshr

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