使用vbscript:
Set fso = CreateObject("Scripting.FileSystemObject")
l1 = fso.OpenTextFile("C:\path\to\log1.txt").ReadAll
l2 = fso.OpenTextFile("C:\path\to\log2.txt").ReadAll
Set re = New RegExp
re.MultiLine = True
're.IgnoreCase = True 'uncomment if you want case-insensitive matches
searchString = InputBox("Enter search string.")
re.Pattern = "\\\\(\S+)\s*" & searchString
For Each m1 In re.Execute(l1)
re.Pattern = "^" & m1.SubMatches(0) & "\s*(\S+)"
For Each m2 In re.Execute(l2)
WScript.Echo m2.SubMatches(0)
Next
Next
运行脚本,cscript.exe
您可以从命令提示符复制输出。
如果您的输入文件非常大(例如,大小超过 1 GB),读取文件的全部内容可能会由于内存耗尽而导致性能下降。在这种情况下,最好逐行处理文件:
Set fso = CreateObject("Scripting.FileSystemObject")
Set re = New RegExp
're.IgnoreCase = True 'uncomment if you want case-insensitive matches
searchString = InputBox("Enter search string.")
re.Pattern = "\\\\(\S+)\s*" & searchString
Set f = fso.OpenTextFile("C:\path\to\log1.txt")
Do Until f.AtEndOfStream
For Each m In re.Execute(f.ReadLine)
match = m.SubMatches(0)
Exit Do
Next
Loop
f.Close
If IsEmpty(match) Then WScript.Quit 'no match found
re.Pattern = "^" & match & "\s*(\S+)"
Set f = fso.OpenTextFile("C:\path\to\log2.txt")
Do Until f.AtEndOfStream
For Each m In re.Execute(f.ReadLine)
WScript.Echo m.SubMatches(0)
Exit Do
Next
Loop
f.Close
这可以通过将文件处理封装在一个函数中来简化:
Set fso = CreateObject("Scripting.FileSystemObject")
Function FindMatch(filename, pattern)
Set re = New RegExp
re.Pattern = pattern
're.IgnoreCase = True 'uncomment if you want case-insensitive matches
Set f = fso.OpenTextFile(filename)
Do Until f.AtEndOfStream
For Each m In re.Execute(f.ReadLine)
FindMatch = m.SubMatches(0)
Exit Do
Next
Loop
f.Close
End Function
searchString = InputBox("Enter search string.")
match1 = FindMatch("C:\path\to\log1.txt", "\\\\(\S+)\s*" & searchString)
If IsEmpty(match1) Then WScript.Quit 'no match found
match2 = FindMatch("C:\path\to\log2.txt", "^" & match1 & "\s*(\S+)")
If Not IsEmpty(match2) Then WScript.Echo match2
不过,对于只有 500 行的文件,我会坚持使用第一个版本,因为代码要简单得多。
顺便说一句,如果您想将找到的匹配复制到剪贴板,您可以直接从脚本中执行此操作,如下所示:
Set ie = CreateObject("InternetExplorer.Application")
ie.Navigate("about:blank")
While ie.Busy : WScript.Sleep 100 : Wend
ie.document.ParentWindow.ClipboardData.SetData "text", m.SubMatches(0)
ie.Quit
但是,您需要添加about:blank
到本地 Intranet 区域才能使其正常工作(Allow Programmatic clipboard access
必须启用安全设置)。