我有一个C#控制台程序,其主要功能应该使用户grep行/列来自日志文本文件。
用户希望在文本文件中的一个示例中重复一组从特定日期等开始的所有相关行。“星期二2004年8月3日22:58:34”到“星期三2004年8月4日00:56:48”。因此,在处理之后,程序将输出两个日期之间在日志文本文件中找到的所有数据。
有人可以提供一些我可以用来grep或创建过滤器以从文件中检索必要的文本/数据的代码的建议吗?谢谢!
C#程序文件:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
namespace Testing
{
class Analysis
{
static void Main()
{
// Read the file lines into a string array.
string[] lines = System.IO.File.ReadAllLines(@"C:\Test\ntfs.txt");
System.Console.WriteLine("Analyzing ntfs.txt:");
foreach (string line in lines)
{
Console.WriteLine("\t" + line);
// ***Trying to filter/grep out dates, file size, etc****
if (lines = "Sun Nov 19 2000")
{
Console.WriteLine("Print entire line");
}
}
// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}
}
}
Run Code Online (Sandbox Code Playgroud)
日志文本文件示例:
Wed Jul 21 2004 16:58:48 499712 m... r/rrwxrwxrwx 0 0 8360-128-3
C:/Program Files/AccessData/Common Files/AccessData LicenseManager/LicenseManager.exe
Tue Aug 03 2004 22:58:34 23040 m... r/rrwxrwxrwx 0 0 8522-128-3
C:/System Volume Information/_restore{88D7369F-4F7E-44D4-8CD1-
F7FF1F6AC067}/RP4/A0002101.sys
23040 m... r/rrwxrwxrwx 0 0 9132-128-3
C:/WINDOWS/system32/ReinstallBackups/0003/DriverFiles/i386/mouclass.sys
23040 m... r/rrwxrwxrwx 0 0 9135-128-4 C:/System Volume
Information/_restore{88D7369F-4F7E-44D4-8CD1-F7FF1F6AC067}/RP4/A0003123.sys
23040 m... r/rrwxrwxrwx 0 0 9136-128-3
C:/WINDOWS/system32/drivers/mouclass.sys
Tue Aug 03 2004 23:01:16 196864 m... r/rrwxrwxrwx 0 0 4706-128-3
C:/WINDOWS/system32/drivers/rdpdr.sys
Tue Aug 03 2004 23:08:18 24960 m... r/rrwxrwxrwx 0 0 8690-128-3
C:/WINDOWS/system32/drivers/hidparse.sys
Run Code Online (Sandbox Code Playgroud)
您可以使用Regex比string.Contains允许的方式丰富的方式来选择匹配的行。
不确定为什么要重新发明findstr.exe。
对于大文件,您可能会发现File.ReadLines(仅适用于.Net 4)的性能更好-读取相同的行,但允许您在foreach或其他IEnumerable情况下进行处理,而无需立即将整个文件加载到RAM中。