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.
8 Answers
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 offturns off printing of each command to the console@at the beginning of the remaining lines stops printing of theechocommand itself, but does not suppressechooutput. (It allows the rest of the line after@echoto display.- 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.txtuses one>to overwrite any file that already exists with new content. - The remaining
@echostatements use two>>characters to append to the text file (add to), instead of overwriting it. - The
type test.txtsimply types the file output to the command window.
Comments
It's easier to use only one code block, then you only need one redirection.
(
echo Line1
echo Line2
...
echo Last Line
) > filename.txt
7 Comments
... to echo ... to make it executable. I don't understand why it doesn't append to an existing file.>> filename.txt, for creating a new file use > filename.txtecho "blahblah"> txt.txt will erase the txt and put blahblah in it's place
echo "blahblah">> txt.txt will write blahblah on a new line in the txt
I think that both will create a new txt if none exists (I know that the first one does)
Where "txt.txt" is written above, a file path can be inserted if wanted. e.g. C:\Users\<username>\desktop, which will put it on their desktop.
3 Comments
'%~dp0 would...) @echo off
(echo this is in the first line) > xy.txt
(echo this is in the second line) >> xy.txt
exit
The two >> means that the second line will be appended to the file (i.e. second line will start after the last line of xy.txt).
this is how the xy.txt looks like:
this is in the first line
this is in the second line
Comments
- You can use
copy conto write a long text Example:
C:\COPY CON [drive:][path][File name]
.... Content
F6
1 file(s) is copied
My solution is similar to jeb's brilliant answer, but it requires just one additional line to be added to an existing text file so there's no need to add echo in front of each line.
(for /F "tokens=* skip=1" %%F in ('type %~0') do (echo %%F >> %~n0.txt)) & exit
Line1
Line2
Last Line
When saved as "sometext.bat" this will create a file "sometext.txt" with the content:
Line1 Line2 Last Line
echo "some text here" >> myfile.txt