使用C#搜索文本文件并显示包含搜索关键字的行号和完整行

17

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

4个回答

25

这是从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();

现在,您可以指导我如何将其导出到Excel。即行和行号。 - Chitresh
嗯...你想要行号在一个单元格中,实际行在另一个单元格中吗?如果是这样,在那里不要用冒号 (":") 分隔,而是用逗号 (",") 分隔,然后让 Excel 将其读取为 CSV 文件(逗号分隔值)。 - PeterM
不,我需要在应用程序本身中构建功能才能导出到Excel(要求如此)...请帮忙。 - Chitresh
我不知道如何做。我会在网上搜索C#导出Excel,或者我会发一个新的问题来询问。 - PeterM
еңЁ.NET 4дёӯпјҢеҸҜд»ҘйҖҡиҝҮдҪҝз”Ёforeach(var line in File.ReadLines("c:\\test.txt"))жҳҫзқҖз®ҖеҢ–д»Јз ҒпјҢж— йңҖдҪҝз”ЁStreamReaderе’ҢCloseгҖӮ - Roman Starkov

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,它可以消除使用 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

1

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

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

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

如果您正在针对特定问题使用临时解决方案,则两种替代方法都可以轻松使用。如果您正在编写其他人(或其他环境)使用的程序,请注意特定文化差异。

哦,我现在刚想起来:您可以使用XML编写电子表格,只需使用.NET包即可。几年前我用C# .NET 2.0做过这件事。


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

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接