在 vb 中搜索文本文件中的字符串并打印行 [英] search for string in text file in vb and print lines

查看:65
本文介绍了在 vb 中搜索文本文件中的字符串并打印行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 VB 的新手,尽管有人可以帮助我解决当前的情况

Hi I am new to VB and just though if someone could help me in my current scenario

我有一个名为 shar.txt 的文本文件
它有 6 行.

I have a text file named shar.txt
It has 6 lines in it.

我是一名新学生
我正在学习VB
请朋友帮帮我
朋友在我们的生活中总是很重要
感谢您的支持
永远感谢你

I am a new student
I am learning VB
Please help me friends
Friends always matter in our life
Thank You for your support
Always grateful to you

我想要一个脚本来读取此文本文件并查找诸如Friends"、support"之类的字符串,并在同一位置的另一个文本文件中打印包含这些字符串的行,例如sha.txt"

I want a script which reads this text file and look for the string such as "Friends", "support" and print the lines containing those strings in another text file at the same location say "sha.txt"

我一直尝试到这一点,但在中途迷路了.

I tried till this point but lost my way i mid.

请有人帮助我.
谢谢

Please someone help me.
thanks

Sub ReadToTextFile()
Dim strPattern1 As String    
Dim strPattern2 As String    
H1 As String    
H2 As String    
strPattern1 = "friends"    
strPattern2 = "support"    


Set objFileToRead = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\Users\sonu\Desktop\auto\shar.txt", 1, True)    
Do Until
 objFileToRead.AtEndOfStream        
    strLine = objFileToRead.ReadLine        
    ElseIf 
InStr(strLine, strPattern1) > 0    
 Then        
        Wscript.Echo strLine    
                H1 = strLine    
                ElseIf 
InStr(strLine, strPattern2) > 0        
 Then        
                Wscript.Echo strLine    
                H2 = strLine    
           End If    

    End If    
Loop    

Wscript.Echo H2    

Set objFileToRead = Nothing    

End Sub    

推荐答案

这个网站的一个非常糟糕的问题.您最好花一些时间阅读规则.

A very bad formed question for this site. It's good for you to spend some time to read the rules.

无论如何,这是我的.

Const ForReading = 1, ForWriting = 2
Dim FSO, FileIn, FileOut, strTmp

Set FSO     = CreateObject("Scripting.FileSystemObject")
Set FileIn  = FSO.OpenTextFile("shar.txt", ForReading)
Set FileOut = FSO.OpenTextFile("sha.txt", ForWriting, True)

Do Until FileIn.AtEndOfStream
    strTmp = FileIn.ReadLine
    If Len(strTmp) > 0 Then
        If InStr(1, strTmp, "Friends", vbTextCompare) > 0 _
        Or InStr(1, strTmp, "support", vbTextCompare) > 0 Then
            FileOut.WriteLine strTmp
        End If
    End If
Loop

FileIn.Close
FileOut.Close

关于您使用数组的问题...

About your question for using arrays...

' an example array
arWords = Array("friends", "support", "xyz")
' modified Do..Loop
Do Until FileIn.AtEndOfStream
    strTmp = FileIn.ReadLine
    If Len(strTmp) > 0 Then
        For i = 0 To UBound(arWords)
            If InStr(1, strTmp, arWords(i), vbTextCompare) > 0 Then
                FileOut.WriteLine strTmp
                Exit For
            End If
        Next
    End If
Loop

干杯!

这篇关于在 vb 中搜索文本文件中的字符串并打印行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆