1

我有 300 000 行的 .txt 文件。有没有办法从该文件中提取特定的字符串(行)并保存在另一个 .txt 或 excel 中仅提取的行?我谈论日志文件,我在其中保存一些请求,每个请求都花费时间。我想要做的是只提取每个请求的时间,然后我将计算平均时间。

希望你们明白我在说什么。

编辑: .txt 文件的格式是纯文本,每个请求都以。所以我有:

Starting date
//body of response from server
End date
Time: 3150,0792 ms <--- time taken

所以,我有 10 000 个请求和 10 000 个响应。我只需要提取每个时间,因为手动滚动整个 .txt 文件并检查每个时间将花费我很多时间。

4

5 回答 5

4

你可以通过文件类来实现它

using (StreamWriter sw = File.AppendText("File2.txt")) 
{
    foreach (string line in File.ReadLines(@"d:\File1.txt"))
    {
        if (line.Contains("TheWordInLine"))//This is the line you want by matching something
        {
                sw.WriteLine("line);
        }
    }
}
于 2012-07-04T08:20:31.720 回答
4

您可以尝试使用MemoryMappedFileTextReader组合。MMF 允许您访问大文件,文本阅读器允许您以逐行方式处理文件。

using (var mmf = 
            MemoryMappedFile.CreateFromFile(@"c:\large.data", FileMode.Open
{
    using (MemoryMappedViewStream stream = mmf.CreateViewStream())
    {
        TextReader tr = new StreamReader(stream);
        while ((line = sr.ReadLine()) != null) 
        {
            Console.WriteLine(line);
        }
    }
}
于 2012-07-04T08:27:43.483 回答
3

当然,您可以使用StreamReader / StreamWriter

using (var input = File.OpenText("input.log"))
using (var output = File.CreateText("output.log"))
{
    string line;
    while ((line = input.ReadLine()) != null)
    {
        if (SomeConditionOnLine(line))
        {
            output.WriteLine(line);
        }
    }
}

这将逐行读取输入文件,因此一次在内存中只有一行,如果该行满足您正在寻找的某些条件,则将其写入输出文件。它会很快并且消耗很少的内存,并且适用于巨大的输入文件。

于 2012-07-04T08:22:20.143 回答
3
    private void extract_lines(string filein, string fileout)
    {
        using (StreamReader reader = new StreamReader(filein))
        {
            using (StreamWriter writer = new StreamWriter(fileout))
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    if (line.Contains("what you looking for"))
                    {
                        writer.Write(line);
                    }
                }
            }
        }
    }
于 2012-07-04T08:26:19.827 回答
2

正如其他人已经说过的那样,有一个格式示例会很有用。无论如何,也许你会发现这个工具很有用:

http://filehelpers.sourceforge.net/

我在工作中使用它,它允许您解析和写入不同的文件格式。希望能帮助到你

于 2012-07-04T08:21:44.700 回答