批处理或VB脚本向文件中添加3行文本

时间:2011-06-06 15:47:50

标签: file-io vbscript batch-file

我有一个我想自动化的过程,但我不擅长Bat和/或vb脚本。我希望这里有人可以给我一两个指针。

以下是手动流程:

  1. 打开文件
  2. 搜索此文字: refname =“Microsoft.VSTS.Build.IntegrationBuild”
  3. 走3行。
  4. 在当前行下方附加此文字:           
  5. 保存文件
  6. 如果有人对如何做到这一点有任何建议,我很乐意听到。

3 个答案:

答案 0 :(得分:2)

这非常快速和肮脏,但它确实有效,应该让你开始。

Const ForReading = 1
Const ForWriting = 2

Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile("C:\MyTestFile.txt", ForReading, False)

findText = "rename=""Microsoft.VSTS.Build.IntegrationBuild"""
Do
  line = f.ReadLine
  position = InStr(1, line, findText, vbTextCompare)
  output = output & line & vbCrLf
Loop While position = 0    

output = output & f.Readline & vbCrLf
output = output & f.Readline & vbCrLf
output = output & f.Readline & vbCrLf
output = output & "YOUR TEXT HERE" & vbCrLf

Do While f.AtEndOfStream <> True
  output = output & f.Readline & vbCrLf
Loop

f.Close

Set f = fso.OpenTextFile("C:\MyOutputFile.txt", ForWriting, True)
f.Write output
f.close

答案 1 :(得分:1)

以此为出发点

    @echo off
    setlocal enabledelayedexpansion
    set /a countlin=0
    for /f "tokens=*" %%a in (a.txt) do (
      if '%%a'=='refname="Microsoft.VSTS.Build.IntegrationBuild"' (
        set /a countlin=1
      ) else (
        if /I !countlin! neq 0 (
          if /I !countlin! equ 4 (
           echo Add here whatever you want
           set /a countlin=0
          ) else ( 
              set /a countlin+=1
          )
        )
      )   
      echo %%a
    )

这个批处理文件遍历a.txt文件的所有行,当它找到所需的字符串时,它开始计算行数,当达到所需的行数时,它会回显所需的输出行。

如需进一步说明,请参阅help forhelp sethelp if

答案 2 :(得分:0)

RegExp解决方案(并入测试驱动程序):

  Dim sNewTxt : sNewTxt    = "abracadabra" & vbCrLf
  Dim reEdit  : Set reEdit = New RegExp
  reEdit.Pattern = Join(Array( _
        "(" _
      , "[\S\s]*?" _
      , "refname=""Microsoft.VSTS.Build.IntegrationBuild""" _
      , "[\S\s]*?\r\n" _
      , "[\S\s]*?\r\n" _
      , "[\S\s]*?\r\n" _
      , "[\S\s]*?\r\n" _
      , ")" _
      , "(" _
      , "[\S\s]*?" _
      , ")" _
  ), "")
  Dim sFolder : sFolder    = "..\testdata\6254577"
  Dim oFile, s1, s2
  For Each oFile In goFS.GetFolder(sFolder).Files
      Select Case Left(oFile.Name, 1)
        Case "a"
          s1 = oFile.OpenAsTextStream().ReadAll()
          s2 = reEdit.RePlace(s1, "$1" & sNewTxt & "$2")
          goFS.CreateTextFile(goFS.BuildPath(sFolder, Replace(oFile.Name, "a", "c"))).Write s2
        Case "c"
          s1 = oFile.OpenAsTextStream().ReadAll()
          s2 = goFS.OpenTextFile(goFS.BuildPath(sFolder, Replace(oFile.Name, "c", "b"))).ReadAll()
          If s1 = s2 Then
             WScript.Echo "ok", oFile.Name
          Else
             WScript.Echo "not ok", oFile.Name
             WScript.Echo s1
             WScript.Echo "-----------"
             WScript.Echo s2
             WScript.Echo "==========="
          End If
      End Select
  Next

它利用了非匹配输入上的.Replace不会改变输入的事实。这使得它比上述解决方案更加强大。