1

我将如何进入文本文件找到某个字符,然后替换该字符所在的整行?

这是文本文件的示例:

    line1
    example line2
    others
    ......
    ....
    id: "RandomStr"
    more lines
    ...

我需要找到该行"id"并替换它。编辑后的文本文件应为:

    line1
    example line2
    others
    ......
    ....
    "The correct line"
    more lines
    ...
4

2 回答 2

2

首先,您需要阅读文本文件的每一行,如下所示:

For Each line As String In System.IO.File.ReadAllLines("PathToYourTextFile.txt")

Next

接下来,您需要搜索要匹配的字符串;如果找到,则将其替换为替换值,如下所示:

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

最后,将数据写回文件,如下所示:

System.IO.File.WriteAllLines("PathToYourOutputFile.txt", outputLines.ToArray(), Encoding.UTF8)
于 2013-08-16T04:33:25.850 回答
1

首先将该行与正则表达式匹配。然后,如果匹配成功,则输出新行。我不知道 VB.net,但 C# 中的函数类似于:

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);
            }
        }
    }
}

然后你会这样称呼它:

replaceLines(@"C:\temp\input.txt", @"c:\temp\output.txt", "id", "The correct line");

希望这可以帮助。

于 2013-08-16T04:34:10.453 回答