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

34

我该如何在Windows批处理文件中实现以下操作?

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

请注意,我希望将此作为批处理脚本的一部分来执行,因此无法使用con+Enter(至少我可能可以,但我不知道如何在批处理脚本中模拟Enter键)。

谢谢!

3个回答

65

使用输出重定向符号>>>

echo one>%file%
echo two>>%file%
echo three>>%file%

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

>%file%  echo one
>>%file% echo two
>>%file% echo three

你也可以使用:

(
    echo one
    echo two
    echo three
) >%file%

6
对于空白行,可以使用 echo. 或者 echo= 或者 echo: 等命令(cmd.exe 识别许多分隔符,不仅限于空格。到目前为止,我发现在 echo 命令中可以使用的分隔符包括:.、;、,、/、=、+、\)。 - user1686
2
所选答案省略了stderr - 虽然在这个问题中可能不是必要的,但是当重定向输出时,您应该考虑如果命令行应用程序将错误输出到stderr,则仅使用>或>>重定向输出将无法捕获错误。 您需要使用2>&1或2>>&1将其重定向到同一文件,或指定不同的文件。例如: net /? > StdOutLog.txt 2> StdErrLog.txt (net命令有点奇怪,因为它将输出显示到标准错误 - net子命令显示到标准输出,因此net use > stdOutLog.txt 2> StdErrLog.txt将在stdOutLog.txt中找到数据) - Multiverse IT
1
@grawity echo. 和其他大多数命令可能会与现有文件“echo”发生冲突,并且它们总是强制进行文件系统访问,echo( 似乎是“安全”的。 - jeb
1
@grawity:你是对的,不是所有变体都会检查文件,但它们也不会对其他“问题”(如/?on)“安全”。在这里讨论了echo. fails - jeb
1
@jeb:重新测试了我的“安全”列表;=echo=/? 失败,但其余的都可以。 (关于您在论坛上的帖子:对于 /,您可以使用 echo//?,而不是 echo/?。对于单个问号,只需使用 echo ? 即可。但是现在任何理智的人都会将脚本移植到另一种语言中(提问者已经安装了Python)。无论如何,这就是我会做的事情。) - user1686
显示剩余2条评论

8
echo Line 1^

Line 2^

Line 3 >textfile.txt

请注意双换行符以强制输出:

请注意双换行符以强制输出:

Line1
Line2
Line3

另外:

(echo Line 1^

Line 2^

Line 3)>textfile.txt

-1

如果你想用一行代码实现,这里有一个更复杂的例子

  • 我用\n模拟回车
  • 我转义括号中的特殊字符
  • 我将\n替换为批处理所需的内容
set text=Cols:\n- Port de Lers (1517m) avec le col d'Agnès (1570m)\n- Col de la Core (1395m)\n- Col de Menté (1349m)\n- Col de Peyresourde (1569m)\n- Col du Tourmalet (2115m)\n- Col d'Aubisque (1709m)\n- Col de Marie-Blanque (1035m)\n- Col de Labays (1354m)
set "text=%text:(=^(%" :: I escape special character for parenthesis
set "text=%text:)=^)%" :: I escape special character for parenthesis
set "text=%text:\n= >> temp.txt & echo %" :: I replace the `\n` with what is needed in batch 
set "text=%text:"=%"
if exist "temp.txt" rm temp.txt :: just remove the file if exist to avoid to append in it
echo %text% >> temp.txt
cat temp.txt :: print result

C:\ > cat temp.txt
Cols:
- Port de Lers (1517m) avec le col d'Agnès (1570m)
- Col de la Core (1395m)
- Col de Menté (1349m)
- Col de Peyresourde (1569m)
- Col du Tourmalet (2115m)
- Col d'Aubisque (1709m)
- Col de Marie-Blanque (1035m)
- Col de Labays (1354m)

如果您想删除最后的\r\n,请使用truncate -s -2 temp.txt

在Windows上安装git以便能够使用truncate


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接