Windows:在批处理文件中,将多行写入文本文件?

28 windows command-line batch-file

如何在Windows批处理文件中执行以下操作?

  1. 写入名为subdir/localsettings.py的文件
  2. 覆盖所有现有内容......
  3. ......有多行文字......
  4. ...包括一个字符串"[当前工作目录]/subdir"(我认为可能是%cd%/subdir?)

请注意,我想将此作为批处理脚本的一部分,因此我不能使用con+ Enter(至少,也许我可以,但我不知道如何模拟Enter作为批处理脚本的一部分).

谢谢!

gra*_*ity 52

使用输出重定向>>>

echo one>%file%
echo two>>%file%
echo three>>%file%
Run Code Online (Sandbox Code Playgroud)

或者以更易读的方式:(在cmd.exe,使用" echo one >%file%"将包括之前的空格>.)

>%file%  echo one
>>%file% echo two
>>%file% echo three
Run Code Online (Sandbox Code Playgroud)

你也可以使用:

(
    echo one
    echo two
    echo three
) >%file%
Run Code Online (Sandbox Code Playgroud)

  • 对于空行,`echo`或`echo =`或`echo:`或...(有很多分隔符,`cmd.exe`识别;不仅仅是空格.到目前为止,我已经发现了`. ,/ = + \`with`echo`) (4认同)
  • 选择的答案省略了stderr - 虽然在这个问题中可能没有必要,但是当重定向输出时,您应该考虑如果命令行应用程序向stderr输出错误,只需使用>或>>重定向输出就不会捕获错误.您需要使用2>&1或2 >>&1重定向到同一文件,或指定其他文件.例如:net /?> StdOutLog.txt 2> StdErrLog.txt(net命令有点奇怪,它显示输出为标准错误 - net子命令显示为标准输出,因此net use> stdOutLog.txt 2> StdErrLog.txt将在stdOutLog中查找数据.文本) (2认同)

acc*_*ted 7

echo Line 1^

Line 2^

Line 3 >textfile.txt
Run Code Online (Sandbox Code Playgroud)

Note the double new-lines to force the output:

Line1
Line2
Line3
Run Code Online (Sandbox Code Playgroud)

Also:

(echo Line 1^

Line 2^

Line 3)>textfile.txt
Run Code Online (Sandbox Code Playgroud)