tags:

views:

33

answers:

2

In my bat script, what do I use to open a file called open.txt and add the following line to the top

SOME TEXT TO BE ADDED

Can small edits like this be handled in a .bat script

+3  A: 

you can do just simple echos and redirection. but if you can download sed for windows, here's how you can do it

C:\test> sed -i.bak "1 i text" file

If download is impossible, you can use vbscript

strAddText= WScript.Arguments(0)
strFileName = WScript.Arguments(1)
Set objFS = CreateObject( "Scripting.FileSystemObject" )
Set objFile = objFS.OpenTextFile(strFileName)
WScript.Echo strAddText
Do Until objFile.AtEndOfStream
    WScript.Echo objFile.ReadLine
Loop    

To use:

C:\test> cscript //nologo myscript.vbs "text to add" myfile  > newfile
ghostdog74
+3  A: 

Sure, with something like:

copy original.txt temp.txt
echo.SOME TEXT TO BE ADDED>original.txt
type temp.txt >>original.txt
del temp.txt

The first line makes a temporary copy of the file. The second line overwrites the file with the line you want to add (note particularly the lack of spaces between the text being added and the > redirection operator - echo has a nasty habit of including such spaces).

The third line uses the append redirection operator >> to add the original file to the end of the new one, then the final line deletes the temporary file.

paxdiablo
Thanks, but how do I add a new line after the SOME TEXT TO BE ADDED that I added
Berming
`echo` already puts a line ending in. If you want _another_ line ending (i.e., a blank line), you should also do `echo.>>original.txt` after the first `echo`.
paxdiablo