tags:

views:

22

answers:

1

I'm taking this approach to add a line SOME TEXT TO BE ADDED to the top of an existing file. Is there a way to specify the exact line number to add the new text. For example, before the last line (and add a line break) or after the 3rd line (and add a line break)

copy original.txt temp.txt
echo.SOME TEXT TO BE ADDED>original.txt
type temp.txt >>original.txt
del temp.txt
+4  A: 

Vbscript

strLineNum = WScript.Arguments(0)
strAddText= WScript.Arguments(1)
strFileName = WScript.Arguments(2)
Set objFS = CreateObject( "Scripting.FileSystemObject" )
Set objFile = objFS.OpenTextFile(strFileName)
Do Until objFile.AtEndOfStream
    linenum=objFile.Line
    strLine = objFile.ReadLine
    If linenum = CInt(strLineNum) Then
        WScript.Echo strAddText
    End If
    WScript.Echo strLine
Loop       
objFile.Close

Usage:

C:\test> cscript //nologo myscript.vbs 2 "text to insert" file >temp
C:\test> ren temp file
ghostdog74
The usage is very simple. Save the bunch of code as a file, such as myscript.vbs. then use the cscript command as described. If your administrator disabled vbscript, then you have to revert to batch. Vbscript is installed by default, so no problems distributing them. BUT since you are a PHP developer, why not do ths with PHP? After all, PHP is way better for file processing than batch and it can do a whole lot more.
ghostdog74
@user131527 Ok, I get it now, I'll try it. Actually PHP wouldn't work in this case because I'm making setup changes related to Windows PATH Environment Variable and just other setup related tasks, so it's outside the scope of the PHP script itself.
Berming
i don't have a problem though.
ghostdog74
You can do it within vbscript by opening a file handle to write. But let's keep it simple. you can redirect the output to a temp file then use `ren` to rename. See edit
ghostdog74