|
-
Oct 17th, 2023, 09:00 AM
#1
Thread Starter
Addicted Member
[RESOLVED] VB.NET search text file and remove only first found duplicate.
Hi All - I am using this code to find and remove duplicates, but now what I need to do is search for the duplicate, but only remove the first duplicate found in the text file. I could have up to 3-4 duplicates in the file. Having a hard time searching for this.
Code:
Dim filename As String = "c:\scripts\scan.txt"
File.WriteAllLines(filename, File.ReadAllLines(filename).Where(Function(l) l <> TB_Search.Text))
-
Oct 17th, 2023, 09:26 AM
#2
Re: VB.NET search text file and remove only first found duplicate.
Your title is a bit different than what your code is doing. It looks like you want to remove only the first instance of a line in a text file that matches the text in your TextBox.
If that's the case, then you can do this:
Code:
Private Sub RemoveMatchingLineFromFile(filename As String, term As String)
Dim lines = New List(Of String)(IO.File.ReadAllLines(filename))
Dim indexToRemove = -1
For index = lines.Count - 1 To 0 Step -1
Dim line = lines(index)
If (line = term)) Then
indexToRemove = index
End If
Next
If (indexToRemove > -1) Then
lines.RemoveAt(indexToRemove)
End If
IO.File.WriteAllLines(filename, lines)
End Sub
' RemoveMatchingLineFromFile("c:\scripts\scan.txt", TB_Search.Text)
This loops from the last line to the first line, sets the index that will be removed if the currently iterated line matches the search term, optionally removes the line, and then updates the file's text.
Edit - I just realized you can make this more concise by using the FindIndex method:
Code:
Private Sub RemoveMatchingLineFromFile(filename As String, term As String)
Dim lines = New List(Of String)(IO.File.ReadAllLines(filename))
Dim indexToRemove = lines.FindIndex(Function(line) line = term)
If (indexToRemove > -1) Then
lines.RemoveAt(indexToRemove)
End If
IO.File.WriteAllLines(filename, lines)
End Sub
It's the same concept only the looping is taken care of under the hood.
Last edited by dday9; Oct 17th, 2023 at 09:34 AM.
-
Oct 17th, 2023, 09:54 AM
#3
Thread Starter
Addicted Member
Re: VB.NET search text file and remove only first found duplicate.
dday9 - Thank you, this is EXACTLY what I needed. Much appreciated
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|