How can I use a batch file to write to a text file?

后端 未结 7 1742
不知归路
不知归路 2020-12-07 07:58

I need to make a script that can write one line of text to a text file in the same directory as the batch file.

7条回答
  •  自闭症患者
    2020-12-07 08:50

    You can use echo, and redirect the output to a text file (see notes below):

    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
    

    Output:

    D:\Temp>WriteText
    
    D:\Temp>type test.txt
    This is a test
    123
    245.67
    
    D:\Temp>
    

    Notes:

    • @echo off turns off printing of each command to the console
    • Unless you give it a specific path name, redirection with > or >> will write to the current directory (the directory the code is being run in).
    • The echo This is a test > test.txt uses one > to overwrite any file that already exists with new content.
    • The remaining echo statements use two >> characters to append to the text file (add to), instead of overwriting it.
    • The type test.txt simply types the file output to the command window.

提交回复
热议问题