2

我有大约 2000 行的日志文件。我已经完成了第一轮格式化。但是,我在将日志格式化为我目前想要的格式时遇到了困难:

当前的:

line1: 9/13/2011 3:58:05 AM, abef, 1234, ...
line2: 9/14/2011 3:58:05 AM, adef, 1234, ...
line3:
line4: 9/15/2011 3:58:05 AM, bcdef, 134, ...
line5: 3) sdad
line6: azd
line7: [] asdsdee234 
line2014: 9/16/2011 3:58:05 AM, abcf, 1234, ...

我想要实现的是清理日志以删除不以日期开头的行。所以需要删除第 3、5、6 和 7 行。

想要的结果:

line1: 9/13/2011 3:58:05 AM, abef, 1234, ...
line2: 9/14/2011 3:58:05 AM, adef, 1234, ...
line3: 9/15/2011 3:58:05 AM, bcdef, 134, ...
line2010: 9/16/2011 3:58:05 AM, abcf, 1234, ...
4

2 回答 2

3
private static IEnumerable<string> ReadOnlyDateTime(string path)
{
    DateTime d;
    string input;
    using (StreamReader stream = new StreamReader(path)) 
    {
        while ((input = stream.ReadLine() != null && DateTime.TryParse(input, out d))
        {
            yield return input;
        }
    }
}

或者

DateTime d;
IList<string> = File.ReadLines(path)
                    .Where(line => DateTime.TryParse(line, out d)
                    .ToList();

然后使用 .dump 结果到磁盘File.WriteAllLines()

于 2012-11-16T05:48:26.873 回答
1

当您在代码中遍历文件的每一行时,您有两个选项来检查日期:

于 2012-11-16T05:36:57.907 回答