I have a text file contains delimited records.
1243;jhhf';982u4k;9u2349;huf8
kij;9238u;98ur23;jfwf;03i24
I need to replace the value of 4th part from every record with the value returned from database or someother source.
Any clue ? expecting VB CODE
Take a look at here( for C# language );
Split string in C#
You could try this (written in C#):
C# release
List<string> newLines = new List<string>();
string[] lines = File.ReadAllLines(filename);
foreach (string line in lines)
{
string[] parts = line.Split(";".ToCharArray());
parts[3] = string_from_db;
newLines.Add(String.Join(";", parts));
}
File.WriteAllLines(filename, newLines.ToArray());
VB.NET release
Dim newLines As List(Of String) = New List(Of String)
Dim lines As String() = File.ReadAllLines(filename)
For Each line As String In lines
Dim parts As String() = line.Split(";")
parts(3) = string_from_db
newLines.Add(String.Join(";", parts))
Next
File.WriteAllLines(filename, newLines.ToArray())
Related
i have textbox with text is "ab1234de524sfe6985dsef456" and i want take all number in this to array
like
arr(0)=1234,
arr(1)=524,
arr(2)=6985,
arr(3)=456
help me, thanks
You can use Regex.Check out following code snippet that is written in c#
string strRegex = #"\d+";
Regex myRegex = new Regex(strRegex, RegexOptions.Singleline);
string strTargetString = #"ab1234de524sfe6985dsef456";
ArrayList list=new ArrayList();
foreach (Match myMatch in myRegex.Matches(strTargetString))
{
if (myMatch.Success)
{
list.Add(myMatch.Value);
}
}
list.Dump();
Converted to Visual Basic:
Dim strRegex As String = "\d+"
Dim myRegex As New Regex(strRegex, RegexOptions.Singleline)
Dim strTargetString As String = "ab1234de524sfe6985dsef456"
Dim list As New ArrayList()
For Each myMatch As Match In myRegex.Matches(strTargetString)
If myMatch.Success Then
list.Add(myMatch.Value)
End If
Next
How would I go into a text file find a certain character then replace the entire line that the character was on?
Here's an example of the text file:
line1
example line2
others
......
....
id: "RandomStr"
more lines
...
I need to find the line with "id" and replace it.
The edited text file should be:
line1
example line2
others
......
....
"The correct line"
more lines
...
First you need to read each line of the text file, like this:
For Each line As String In System.IO.File.ReadAllLines("PathToYourTextFile.txt")
Next
Next, you need to search for the string you want to match; if found, then replace it with replacement value, like this:
Dim outputLines As New List(Of String)()
Dim stringToMatch As String = "ValueToMatch"
Dim replacementString As String = "ReplacementValue"
For Each line As String In System.IO.File.ReadAllLines("PathToYourTextFile.txt")
Dim matchFound As Boolean
matchFound = line.Contains(stringToMatch)
If matchFound Then
' Replace line with string
outputLines.Add(replacementString)
Else
outputLines.Add(line)
End If
Next
Finally, write data back to a file, like this:
System.IO.File.WriteAllLines("PathToYourOutputFile.txt", outputLines.ToArray(), Encoding.UTF8)
First match the line against a regular expression. Then, if the match succeeds, output the new line. I don't know VB.net, but the function in C# would be something like:
void replaceLines(string inputFilePath, string outputFilePath, string pattern, string replacement)
{
Regex regex = new Regex(pattern);
using (StreamReader reader = new StreamReader(inputFilePath))
using (StreamWriter writer = new StreamWriter(outputFilePath))
{
string line;
while ((line = reader.ReadLine()) != null)
{
if (regex.IsMatch(line))
{
writer.Write(replacement);
}
else
{
writer.Write(line);
}
}
}
}
Then you would call it like:
replaceLines(#"C:\temp\input.txt", #"c:\temp\output.txt", "id", "The correct line");
Hope this helps.
I am using Visual Basic.net.
If I have a string that has many lines in it, is it possible to insert a string at a certain line? I see that there is an insert function for strings. Is there a function to insert a string at a certain line of another string?
Is there a function to insert a string at a certain line of another
string?
No, because a string is not a list/array of lines. You have to split it by Environment.NewLine to get an array, ToList to get a List(Of String) which has an Insert method. Then you can use String.Join to put it together after you have inserted it:
Dim lines = MultiLineText.Split({Environment.NewLine}, StringSplitOptions.None).ToList()
lines.Insert(2, "test") ' will throw an ArgumentOutOfRangeException if there are less than 2 lines '
Dim result = String.Join(Environment.NewLine, lines)
There is no string methods that handles a string as a collections of lines. You can use the Insert method, but you have to find out where in the string to put the line yourself.
Example:
' Where to insert
Dim line As Integer = 4
' What to insert
Dim content As String = "asdf"
' Locate the start of the line
Dim pos As Integer = 0
Dim breakLen As Integer = Environment.Newline.Length
For i As Integer = 0 to line
pos = text.IndexOf(Environment.Newline, pos + breakLen)
Next
' Insert the line
text = text.Insert(pos, content + Environment.Newline)
Strings have no idea what a "line" is. A string is only a sequence of characters. What you can do is to convert your string into a list of individual lines (for example as List<string>) and then insert into that list.
List<string> listOfLines = new List<string>();
listOfLines.AddRange(sourceString.Split(new String[] { Environment.NewLine }, StringSplitOptions.None));
listOfLines.Insert(13, "I'm new here");
string result = String.Join(Environment.NewLine, listOfLines);
This is C# code, but I'm pretty sure you can easily convert this to VB.NET.
I have a CSV file with many rows in which I need to update/replace column four's value using VB.NET. There are no headers on the columns so the loop can start on row one.
infile.csv
"value1","value2","value3","value4"
After much googling, there are lots of examples on how to read and write CSV files, but none quite what is needed. I know there are multiple ways to accomplish this task, but a requirement is that it's done with VB.NET. Any help would be greatly appreciated.
Final code ported from Marco's C# answer
Private Sub CSVmod(ByVal strFileName As String, ByVal newFileName As String)
Dim strLines As String() = File.ReadAllLines(strFileName)
Dim strList As New List(Of String)
Dim strReplace As String = "test"
For Each line In strLines
Dim strValues As String() = line.Split(",")
If (strValues.Length = 14) Then
strValues(3) = strReplace
strList.Add(String.Join(",", strValues))
End If
Next
File.WriteAllLines(newFileName, strList.ToArray())
I'm sorry, but I can write it only in C#.
I think you won't find many problems to convert to VB.NET.
Here is my code:
private void SubstFile(string filename, string newFileName)
{
// Reading all rows of the file
string[] lines = File.ReadAllLines(filename);
List<string> list = new List<string>();
foreach (string line in lines)
{
// For every row I split it with commas
string[] values = line.Split(',');
// Check to have 4 values
if (values.Length == 4)
{
// Substitute fourth value
values[3] = "new value";
// Add modified row to list
list.Add(String.Join(",", values));
}
}
// Save list to new file
File.WriteAllLines(newFileName, list.ToArray());
}
VB.NET version:
Private Sub SubstFile(filename As String, newFileName As String)
' Reading all rows of the file
Dim lines As String() = File.ReadAllLines(filename)
Dim list As List(Of String) = New List(Of String)()
For Each line As String In lines
' For every row I split it with commas
Dim values As String() = line.Split(","c)
' Check to have 4 values
If values.Length = 4 Then
' Substitute fourth value
values(3) = "new value"
' Add modified row to list
list.Add(String.Join(",", values))
End If
Next
' Save list to new file
File.WriteAllLines(newFileName, list.ToArray())
End Sub
Use python....one line of code
df = pandas.read_csv('file.csv)
I have a file txt file that holds 3 values each seperated by a space how can i assign each value to its own variable and use that for other things?
as example the numbers might be displayed in the text file as:
-1100.02 -1958.19 0.0
Translating Marco’s C# code to VB:
Dim s As String = File.ReadAllText(filename)
Dim nums As String() = s.Split(" "c)
To get numbers, you need to parse the strings separately. You can use Linq to do this:
Dim numbers As Double() = From num In nums Select Double.Parse(num)
In C#:
string s = File.ReadAllText(filename);
string[] nums = s.Split(' ');
So you can access nums[index] where index should be between 0 and 2.
Note that you MUST check if everything went ok...
If you need you can also try:
foreach (string num in nums)
{
double d = double.Parse(num);
// Here you can do what you want with d
}
Try this:
Dim line as String = "-1100.02 -1958.19 0.0"
Dim values() as Double = Array.ConvertAll(line.Split(New Char() { " "c }, StringSplitOptions.RemoveEmotyEntries), AddressOf Convert.ToDouble)
This will result in values being filled with numbers from the input string (assuming a set of valid numbers on each line).
dim strSplitted() as string = Line.split(" "c)
' strSplitted(0), strSplitted(1) and strSplitted(2) will hold the values.
Line is the line in the file ofcourse :-)
update: code updated according to comments.