我一直在努力为我的问题找到一个合适的解决方案好几天,现在到处寻找。希望你们中的一些人可以指引我走向正确的方向。
我需要在文本文件中找到字符串“OK”,如果我找到“OK”将其保存为变量,则在同一行中提取前2个字符。
我举一个例子来说明你可以在这个文本文件中找到的行:
Debugger
--------------
>h state 2
Health thread state is: POLLING
Health Devices:
Sensor Name State Eval RED Value ( D , M ) Link Active Grp Description
11 ( 2) TEMP ( 1) OK 1 1 21 ( 1, 0) 0xff 0000 0 01-Inlet Ambient (X:1 y:1)
12 ( 2) TEMP ( 1) OK 0 1 40 ( 1, 0) 0xff 0000 0 02-CPU 1 (X:11 y:5)
13 ( 2) TEMP ( 2) MISSING 0 1 0 ( 0, 1) 0xff 0000 0 04-P1 DIMM 1-6 (X:14 y:5)
14 ( 2) TEMP ( 1) OK 0 1 24 ( 1, 0) 0xff r0000 0 05-P1 DIMM 7-12 (X:9 y:5)
15 ( 2) TEMP ( 2) MISSING 0 1 0 ( 0, 1) 0xff 0000 0 06-P2 DIMM 1-6 (X:6 y:5)
16 ( 2) TEMP ( 2) MISSING 0 1 0 ( 0, 0) 0xff 0000 0 07-P2 DIMM 7-12 (X:1 y:5)
17 ( 2) TEMP ( 1) OK 0 1 35 ( 1, 0) 0xff 0000 0 08-HD Max (X:2 y:3)
18 ( 2) TEMP ( 1) OK 0 1 38 ( 1, 0) 0xff 0000 0 10-Chipset (X:13 y:10)
19 ( 2) TEMP ( 1) OK 0 1 24 ( 1, 0) 0xff 0000 0 11-PS 1 Inlet (X:1 y:14)
20 ( 2) TEMP ( 2) MISSING 0 1 0 ( 0, 0) 0xff 0000 0 12-PS 2 Inlet (X:4 y:14)
21 ( 2) TEMP ( 1) OK 0 1 32 ( 1, 0) 0xff 0000 0 13-VR P1 (X:10 y:1)
22 ( 2) TEMP ( 1) OK 0 1 28 ( 1, 0) 0xff 0000 0 15-VR P1 Mem (X:13 y:1)
23 ( 2) TEMP ( 1) OK 0 1 27 ( 1, 0) 0xff 0000 0 16-VR P1 Mem (X:9 y:1)
24 ( 2) TEMP ( 1) OK 0 1 40 ( 1, 0) 0xff 0000 0 19-PS 1 Internal (X:8 y:1)
25 ( 2) TEMP ( 2) MISSING 0 1 0 ( 0, 0) 0xff 0000 0 20-PS 2 Internal (X:1 y:8)
26 ( 2) TEMP ( 2) MISSING 0 1 0 ( 0, 0) 0xff 0000 0 21-PCI 1 (X:5 y:12)
27 ( 2) TEMP ( 2) MISSING 0 1 0 ( 0, 0) 0xff 0000 0 22-PCI 2 (X:11 y:12)
28 ( 2) TEMP ( 2) MISSING 0 1 0 ( 0, 0) 0xff 0000 0
使用下面的代码我可以提取一行中的前两个字符,但我必须从第一次出现“OK”的行中提取2个字符
strLine = objTextFile.ReadLine
objTextFile.Close
'Gets first 2 chars
SerNum = Left(strLine, 2)
寻求帮助......提前致谢...
我未完成的vbscript:
Const ForReading = 1
Dim strSearchFor
strSearchFor = "OK"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile("C:\myFile.txt", ForReading)
For i = 0 to 20
strLine = objTextFile.ReadLine()
If InStr(strLine, strSearchFor) > 0 Then
SensorNumb = Left(strLine, 2)
Exit For
End If
Next
最终代码:
Const ForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile("C:\myFile.txt", ForReading)
For i = 0 to 20
strLine = objTextFile.ReadLine()
If InStr(strLine, "OK") > 0 Then
SensorNumb = Left(strLine, 2)
objTextFile.Close
Exit For
End If
Next
答案 0 :(得分:0)
这个python脚本应该适合你:
lines = [line[:-1] for line in open("MY_FILENAME")]
for i in range(len(lines)):
if lines[i].contains("OK"):
print lines[i][:2]
将其另存为*.py
文件并使用python path/to/python/file
答案 1 :(得分:0)
基本上你想做的是:
InStr
Mid(str, 1, 2)
您应该能够自己将这些链接在一起。