VBScript脚本无法读取文件A下一行,请求技术协助
Fixing VBScript Loop to Read All Lines from File A
Got it, let's break down why your script only grabs the first line of File A—chances are you called ReadLine() once without wrapping it in a loop to keep going until the end of the file. VBScript's TextStream object has a handy AtEndOfStream property we can use to fix this.
Here's a revised script that implements the full loop for File A, plus the matching and writing logic for Files B and C:
' Set your file paths here strFileA = "C:\your\path\fileA.txt" strFileB = "C:\your\path\fileB.txt" strFileC = "C:\your\path\fileC.txt" ' Initialize FileSystemObject Set objFSO = CreateObject("Scripting.FileSystemObject") ' Open File A for reading Set objFileA = objFSO.OpenTextFile(strFileA, 1) ' 1 = Read-only mode ' Open File C for writing (overwrites existing; use 8 instead of 2 to append) Set objFileC = objFSO.OpenTextFile(strFileC, 2, True) ' True = create file if it doesn't exist ' Loop through every line in File A Do Until objFileA.AtEndOfStream ' Get the current line from File A, trim extra spaces to avoid match issues strSearchTerm = Trim(objFileA.ReadLine()) ' Skip empty lines in File A to save unnecessary work If strSearchTerm <> "" Then ' Open File B to search for matches Set objFileB = objFSO.OpenTextFile(strFileB, 1) Do Until objFileB.AtEndOfStream strLineFromB = objFileB.ReadLine() ' Adjust this condition to match your "specified position" requirement ' Example: If the search term is in the first 10 characters, use Left(strLineFromB,10) = strSearchTerm If InStr(strLineFromB, strSearchTerm) > 0 Then ' Write the matching line to File C objFileC.WriteLine(strLineFromB) ' Optional: Uncomment below to stop searching File B after first match for this term ' Exit Do End If Loop ' Don't forget to close File B after each search to prevent file locks objFileB.Close() End If Loop ' Clean up all open files and objects objFileA.Close() objFileC.Close() Set objFSO = Nothing WScript.Echo "Done! Matching lines saved to " & strFileC
Key Improvements:
- Full File A Loop: The outer
Do Until objFileA.AtEndOfStreamloop keeps reading lines until we hit the end of File A. - Trimmed Search Terms: Using
Trim()removes accidental leading/trailing spaces that could break matches. - Empty Line Handling: We skip blank lines in File A to avoid wasted searches.
- Proper File Closing: Closing File B after each search prevents it from being locked, which is crucial since we reopen it for every line in File A.
- Adjustable Match Logic: The
InStr()check is a basic match—tweak this if you need to target a specific position (like a fixed column in a CSV or fixed-width file).
If you need help refining the "specified position" match for File B (e.g., parsing delimited columns), just share more details about File B's structure!
内容的提问来源于stack exchange,提问作者J D
相关产品推荐
相关产品推荐

