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

发布于 2024-10-27 18:26:53 字数 125 浏览 3 评论 0原文

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

孤单情人 2024-11-03 18:26:53

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

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

之后您可以使用类似的技术重新添加第一行:

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

如果您在批处理文件中使用这些内容,请记住将 % 标志:

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

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

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

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"
)
不及他 2024-11-03 18:26:53

这是我的版本。

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

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"
)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文