ThatGuyJay
ThatGuyJay

Reputation: 427

How to find a character and replace the entire line in a text file

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
    ...

Upvotes: 1

Views: 3942

Answers (2)

Karl Anderson
Karl Anderson

Reputation: 34844

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)

Upvotes: 2

Justin R.
Justin R.

Reputation: 24061

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.

Upvotes: 1

Related Questions