17

我需要帮助来使用 c# 搜索文本文件(日志文件)并显示行号和包含搜索关键字的完整行。

4

4 回答 4

24

这是来自:http: //msdn.microsoft.com/en-us/library/aa287535%28VS.71%29.aspx的轻微修改

int counter = 0;
string line;

// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt");
while((line = file.ReadLine()) != null)
{
    if ( line.Contains("word") )
    {
        Console.WriteLine (counter.ToString() + ": " + line);
    }

   counter++;
}

file.Close();
于 2010-03-13T08:17:38.260 回答
15

这个游戏有点晚了,但发生在这篇文章中,我想我会添加一个替代答案。

foreach (var match in File.ReadLines(@"c:\LogFile.txt")
                          .Select((text, index) => new { text, lineNumber = index+ 1 })
                          .Where(x => x.text.Contains("SEARCHWORD")))
{
    Console.WriteLine("{0}: {1}", match.lineNumber, match.text);
}

这使用:

  • File.ReadLines,它消除了对 a 的需要StreamReader,并且它还可以很好地与 LINQ 的Where子句配合使用,以从文件中返回一组过滤的行。

  • Enumerable.Select的重载返回每个元素的索引,然后您可以将其加 1,以获取匹配行的行号。

样本输入:

just a sample line
another sample line
first matching SEARCHWORD line
not a match
...here's aSEARCHWORDmatch
SEARCHWORD123
asdfasdfasdf

输出:

3: first matching SEARCHWORD line
5: ...here's aSEARCHWORDmatch
6: SEARCHWORD123
于 2014-09-23T00:56:11.423 回答
1

要导出 Excel,您可以使用 CSV 文件格式,就像悲观主义者写的那样。如果您不确定要写什么,请尝试在 MS Excel 中输入一些数据,然后单击菜单中的“另存为”选项,然后选择 CSV 作为文件类型。

编写 CSV 文件格式时要小心,因为在某些语言中,分隔值的默认值不是逗号。例如,在巴西葡萄牙语中,默认值是逗号作为小数分隔符,点作为千位分隔符,分号作为分隔值。写的时候要注意文化。

另一种选择是使用水平制表符作为分隔符。尝试编写一个字符串,按 TAB 键,然后按另一个字符串并将其粘贴到 Microsoft Excel 中。它是该程序中的默认分隔符。

如果您对特定问题使用临时解决方案,则可以使用任何一种替代方案而无需过多考虑。如果您正在编程供其他人(或在其他环境中)使用的东西,请注意文化特定的差异。

哦,我现在才想起来:您可以使用 XML 编写电子表格,仅使用 .NET 包即可。几年前我用 C# .NET 2.0 做到了这一点

于 2012-01-11T15:20:25.997 回答
0

我有一个要求,我需要搜索目录列表以查找特定文件类型,其中包含特定搜索词但不包括其他词。

例如,假设您想查看 C:\DEV 并且只找到具有术语“WriteLine”和“Readline”但没有术语“hello”的 .cs 文件。

我决定编写一个小的 c# 实用程序来做到这一点:

这就是你所说的:

class Program
{

    //Syntax:
    //FileSearch <Directory> EXT <ext1> <ext2> LIKE <TERM1> <TERM2>  NOT <TERM3> <TERM4>
    //Example:
    //Search for all files recursively in C:\Dev with an extension of cs that contain either "WriteLine" or "Readline" but not "hello"
    //FileSearch C:\DEV EXT .cs LIKE "WriteLine" "ReadLine" NOT "hello" 
    static void Main(string[] args)
    {
        if (args.Length == 0)
        {
            Console.WriteLine("FileSearch <Directory> EXT <EXT1> LIKE <TERM1> <TERM2>  NOT <TERM3> <TERM4>");
            return;
        }
        
        Search s = new Search(args);
        s.DoSearch();
    }

}

这是实现:

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

class Hit
{
    public string File { get; set; }
    public int LineNo { get; set; }
    public int Pos { get; set; }
    public string Line { get; set; }
    public string SearchTerm { get; set; }

    public void Print()
    {
        Console.WriteLine(File);
        Console.Write("(" + LineNo + "," + Pos + ") ");
        Console.WriteLine(Line);
    }
}


class Search
{
    string rootDir;
    List<string> likeTerms;
    List<string> notTerms;
    List<string> extensions;
    List<Hit> hitList = new List<Hit>();

    //FileSearch <Directory> EXT .CS LIKE "TERM1" "TERM2"  NOT "TERM3" "TERM4" 
    public Search(string[] args)
    {
        this.rootDir = args[0];
        this.extensions = ParseTerms("EXT", "LIKE", args);
        this.likeTerms = ParseTerms("LIKE", "NOT", args);
        this.notTerms = ParseTerms("NOT", "", args);
        Print();
    }


    public void Print()
    {
        Console.WriteLine("Search Dir:" + rootDir);
        Console.WriteLine("Extensions:");
        foreach (string s in extensions)
            Console.WriteLine(s);

        Console.WriteLine("Like Terms:");
        foreach (string s in likeTerms)
            Console.WriteLine(s);

        Console.WriteLine("Not Terms:");
        foreach (string s in notTerms)
            Console.WriteLine(s);

    }

    private List<string> ParseTerms(string keyword, string stopword, string[] args)
    {
        List<string> list = new List<string>();
        bool collect = false;
        foreach (string arg in args)
        {
            string argu = arg.ToUpper();
            if (argu == stopword)
                break;

            if (argu == keyword)
            {
                collect = true;
                continue;
            }
            if(collect)
                list.Add(arg);
        }
        return list;
    }



    private void SearchDir(string dir)
    {
        foreach (string file in Directory.GetFiles(dir, "*.*"))
        {
            string extension = Path.GetExtension(file);

            if (extension != null && extensions.Contains(extension))
                SearchFile(file);
        }
        foreach (string subdir in Directory.GetDirectories(dir))
            SearchDir(subdir);
    }

    private void SearchFile(string file)
    {
      
        using (StreamReader sr = new StreamReader(file))
        {
            int lineNo = 0;
            while (!sr.EndOfStream)
            {
                int pos = 0;
                string term = "";
                string line = sr.ReadLine();
                lineNo++;

                //Look through each likeTerm
                foreach(string likeTerm in likeTerms)
                {
                    pos = line.IndexOf(likeTerm, StringComparison.OrdinalIgnoreCase);
                    if (pos >= 0)
                    {
                        term = likeTerm;
                        break;
                    }
                }

                
                //If found make sure not in the not term
                if (pos >= 0)
                {
                    bool notTermFound = false;

                    //Look through each not Term
                    foreach (string notTerm in notTerms)
                    {
                        if (line.IndexOf(notTerm, StringComparison.OrdinalIgnoreCase) >= 0)
                        {
                            notTermFound = true;
                            break;
                        }
                    }

                    //If not term not found finally add to hitList
                    if (!notTermFound)
                    {
                        Hit hit = new Hit();
                        hit.File = file;
                        hit.LineNo = lineNo;
                        hit.Pos = pos;
                        hit.Line = line;
                        hit.SearchTerm = term;
                        hitList.Add(hit);
                    }
                }

            }
        }
    }


    public void DoSearch()
    {
        SearchDir(rootDir);
        foreach (Hit hit in hitList)
        {
            hit.Print();
        }
    }

}
于 2021-08-31T13:00:52.513 回答