我正在运行一个批处理脚本,以在带有换行符的文本文件中创建一行。 这是出于测试和学习目的。
我有一个名为file.txt
的文本文件,其中包含
this is line one
this is line two
this is line three
我正在使用代码运行批处理脚本,
type file.txt >> output.txt
echo >> output.txt
type file.txt >> output.txt
预期output.txt
,
this is line one
this is line two
this is line three
但是,实际输出进入output.txt
,
this is line one
this is line two
this is line three
(Empty line here)
我所需要的只是每行之间的换行。任何帮助将不胜感激。
答案 0 :(得分:2)
redirection operator >>
将数据附加到重定向目标(您所处的情况下的文件output.txt
),但不能在其中插入任何内容。
要实现目标,您需要逐行阅读输入文件file.txt
。可以通过for /F
loop完成,就像这样:
rem // Write to output file:
> "output.txt" (
rem // Read input file line by line; empty lines and lines beginning with `;` are skipped:
for /F "usebackq delims=" %%L in ("file.txt") do @(
rem // Return current line:
echo(%%L
rem // Return a line-break:
echo/
)
)
这将附加另一个换行符,因此在末尾添加一个空行。 如果要避免这种情况,可以使用一个变量,如下所示:
rem // Reset flag variable:
set "FLAG="
rem // Write to output file:
> "output.txt" (
rem // Read input file line by line; empty lines and lines beginning with `;` are skipped:
for /F "usebackq delims=" %%L in ("file.txt") do @(
rem // Do not return line-break before first line:
if defined FLAG echo/
rem // Return current line:
echo(%%L
rem // Set flag variable to precede every following line by a line-break:
set "FLAG=#"
)
)