I have two text files with various columns, each column is separated by a tab (” “). What I’m trying to do is the following:-
-
If the values in text file 2 column 1 does not contain any value in text file 1 column 1 then add that field to text file 2 and add a 1 to the second column, like so
String 1
-
If the value in text file 2 column 1 already appears in text file 1 columns 1 then just add +1 to the value, so if the above value is already in Text File 1 Column 1 and Text File 2 Column 1 then it would appear as.
String 2
And if it was to happen again then
String 3
and so on.
I have the following coding so far.
Dim lines1 As New List(Of String)(IO.File.ReadAllLines("File1"))
Dim lines2 As New List(Of String)(IO.File.ReadAllLines("File2"))
IO.File.WriteAllLines("File2", lines1.ToArray) & +1)
Update
Dim lines1 As New List(Of String)(IO.File.ReadAllLines("D:\Test\File6.txt"))
Dim lines2 As New List(Of String)(IO.File.ReadAllLines("D:\Test\File5.txt"))
Dim values As New Dictionary(Of String, Integer)()
For Each line As String In lines1
Dim fields() As String = line.Split(" "c)
If fields.Length > 1 Then
values(fields(0)) = Integer.Parse(fields(1))
End If
Next
For Each line As String In lines2
Dim fields() As String = line.Split(" "c)
If fields.Length > 0 Then
If values.ContainsKey(fields(0)) Then
values(fields(0)) = values(fields(0)) + 1
Else
values(fields(0)) = 1
End If
End If
Next
lines1.Clear()
For Each pair As KeyValuePair(Of String, Integer) In values
lines1.Add(pair.Key + " " + pair.Value.ToString())
Next
IO.File.WriteAllLines("D:\Test\File6.txt", lines1.ToArray)
I use the above coding, but it removes the second column?
I would recommend using a dictionary to store the key/value pairs in your first text file. Then, you can easily search and modify the data in the dictionary as you parse the data in the second text file. For instance: