views:

498

answers:

2

Anyone know how to quickly prepend (add two new lines of text) to the start of an existing text file using either VB Script or a Bat file? Most elegant solution gets the tick.

+4  A: 

How about this:

Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")

Set f = fso.OpenTextFile("test.txt", 1)
ReadAllTextFile =   f.ReadAll
Set f = fso.OpenTextFile("test.txt", 2, True)
f.WriteLine("Blaaa")
f.WriteLine("Blaaaa some more...")
f.Write(ReadAllTextFile)

Source: Tek Tips

Jose Basilio
Perfect! Thanks.
MaSuGaNa
+3  A: 

Check José Basilios answer for code and reference to the FSO. You will be using that.

BUT: I wouldn't go the ReadAllTextFile = f.ReadAll route, since that could be a few Gigabytes (who knows?).

INSTEAD:

  1. open a new file
  2. write prepended lines
  3. read line by line from old file, writing into new file
  4. (close both files)
  5. delete old file
  6. rename new file -> old file
Daren Thomas