如何使用批处理文件写入文本文件?

问题描述 投票:0回答:7

我需要制作一个脚本,可以将一行文本写入与批处理文件位于同一目录中的文本文件中。

file batch-file text
7个回答
392
投票

您可以使用

echo
,并将输出重定向到文本文件(请参阅下面的注释):

rem Saved in D:\Temp\WriteText.bat
@echo off
echo This is a test> test.txt
echo 123>> test.txt
echo 245.67>> test.txt

输出:

D:\Temp>写入文本

D:\Temp>输入 test.txt
这是一个测试
123
245.67

D:\临时>

备注:

  • @echo off
    关闭将每个命令打印到控制台
  • 其余行开头的
  • @
    会停止打印
    echo
    命令本身,但不会抑制
    echo
    输出。 (它允许显示
    @echo
    之后的行的其余部分。
  • 除非您为其指定特定的路径名,否则使用
    >
    >>
    进行重定向将写入当前目录(正在运行代码的目录)。
  • @echo This is a test > test.txt
    使用一个
    >
    用新内容覆盖任何已存在的文件。
  • 其余的
    @echo
    语句使用两个
    >>
    字符附加到文本文件(添加到),而不是覆盖它。
  • type test.txt
    只需将文件输出键入命令窗口即可。

152
投票

只使用一个代码块会更容易,那么你只需要一次重定向。

(
  echo Line1
  echo Line2
  ...
  echo Last Line
) > filename.txt

32
投票

echo "blahblah"> txt.txt
将删除文本并将 blahblah 放在它的位置

echo "blahblah">> txt.txt
将在txt中的新行中写入blahblah

我认为如果不存在的话,两者都会创建一个新的txt(我知道第一个是)

上面写“

txt.txt
”的地方,可以根据需要插入文件路径。例如
C:\Users\<username>\desktop
,这会将其放在桌面上。


16
投票
    @echo off

    (echo this is in the first line) > xy.txt
    (echo this is in the second line) >> xy.txt

    exit

两个

>>
表示第二行将被追加到文件中(即第二行将在 xy.txt 的最后一行之后开始)。

这就是

xy.txt
的样子:

this is in the first line
this is in the second line

4
投票

@回声关闭 使用批处理文件编写标题 颜色 0a

echo 示例文本 > 文件名.txt echo 其他文本 >> 文件名.txt

@ECHO OFF
Title Writing Using Batch Files
color 0a

echo Example Text > Filename.txt
echo Additional Text >> Filename.txt

3
投票
  • 您可以使用
    copy con
    写长文本
  • 示例:

    C:\COPY CON [驱动器:][路径][文件名]

    ...内容

    F6

    已复制 1 个文件


1
投票
@echo off

echo Type your text here.

:top

set /p boompanes=

pause

echo %boompanes%> practice.txt

希望这有帮助。你应该更改字符串名称(不知道它叫什么)和文件名

© www.soinside.com 2019 - 2024. All rights reserved.