找到线和&编辑它

时间:2009-07-12 09:24:32

标签: vbscript batch-file edit text-files lines

我在这上面贴了另外一个,但我不得不编辑它...

批处理(也许包括VBScript)可以在txtfile中找到第29行......它应该编辑这一行。

如果第29行是这样的:'option = 21',它应该将其更改为'option = 22'

问题是这条线位于文件的更多位置。所以它应该只编辑第29行......

操作方法???

[请不要自定义程序;;;它应该由每个用户完成而无需安装好的东西。]

3 个答案:

答案 0 :(得分:3)

这不是你通常批量做的事情,但它相当简单:

@echo off
setlocal enableextensions enabledelayedexpansion

rem the input file
set inputfile=file.txt

rem temporary file for output, we can't just write into the
rem same file we're reading
set tempfile=%random%-%random%.tmp

rem delete the temporary file if it's already there
rem shouldn't really happen, but just in case ...
copy /y nul %tempfile%

rem line counter
set line=0

rem loop through the file
for /f "delims=" %%l in (%inputfile%) do (
    set /a line+=1
    if !line!==29 (
        rem hardcoded, at the moment, you might want to look
        rem here whether the line really starts with "options"
        rem and just put another number at the end.
        echo option=22>>%tempfile%
    ) else (
        echo %%l>>%tempfile%
    )
)

del %inputfile%
ren %tempfile% %inputfile%

endlocal

如果你想适应它,它应该指向你的大方向。

答案 1 :(得分:0)

我看到你要求vb脚本,
使用AWK,它会像这样,
也许它会帮助你编码vb

awk'{if(FNR == 29){gsub(/ option = 21 /,“option = 22”); print} else {print $ 0;}}'input.txt> output.txt的

没试过,所以可能有一些温和的故障......

  1. FNR=29将仅在第29行检查处理gsub
    • gsub将使用option=21
    • 替换该行中的所有option=22次出现
    • 其他行将通过

答案 2 :(得分:0)

这是一个vbscript

Set objFS = CreateObject("Scripting.FileSystemObject")
strFile = "c:\test\file.txt"
Set objFile = objFS.OpenTextFile(strFile)
Do Until objFile.AtEndOfStream
    linenum = objFile.Line
    strLine = objFile.ReadLine
    If linenum = 29 Then
        strLine = Replace(strLine,"option=21","option=22")
    End If
    WScript.Echo strLine
Loop    

使用方法:

c:\test> cscript /nologo myscript.vbs > newfile
c:\test> ren newfile file.txt