【问题标题】:Find the line & edit it找到该行并对其进行编辑
【发布时间】:2009-07-12 09:24:31
【问题描述】:

我在此发布了另一个,但我不得不对其进行大量编辑......

问题是 Batch(可能包括 VBScript)可以在 txtfile 中找到第 29 行...它应该编辑这一行。

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

问题在于该行在文件中的位置更多。所以它应该只编辑第 29 行...

怎么做???

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

【问题讨论】:

  • 你不能在用户登录时通过 gpo 或其他方式推送吗?或者这也不是一个理想的情况?基本上,从公共网络共享复制带有正确文本的文件并覆盖用户计算机上的文件,无论该特定文件在哪里?

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


【解决方案1】:

这不是您通常批量执行的操作,但它相当简单:

@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

如果你想调整它,它应该为你指明大方向。

【讨论】:

  • 是的,问题是什么; 'option=22' 应更改为 '
  • 我一直在寻找这个......谢谢!我希望我能给你我所有的赏金,因为我无法告诉你我为此尝试了多长时间。
【解决方案2】:

我看到您要求提供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=22 替换行上出现的任何option=21
    • 其他行将通过

【讨论】:

  • 是的,我刚刚修复了一些我在视觉上发现的错误。只想描述方案;我相信 VB 也可以做到这一点。
  • awk 命令可以缩短:gawk "FNR==29{gsub(/option=21/,\"option=22\")}1" file.txt
【解决方案3】:

这是一个 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-04
    • 1970-01-01
    • 1970-01-01
    • 2015-10-14
    • 2021-08-04
    相关资源
    最近更新 更多