在文件中查找文本并检索行号

我试图(以编程方式)查找对特定字符串的引用,即大量VB6文件中的“LOCK_ID”。 为了帮助人们直接导航到参考,我还想检索匹配的行号。 即:

  1. 搜索所有VB6文件以供参考
  2. 如果找到引用,我想检索引用所在的行号。

如果没有打开目录中的每个文件并遍历文件并记住我正在检查搜索词的哪一行,是否有更快/更简单的方法来实现这一目标?

有很多工具可以做到这一点。 我会在编辑时将它们列在编辑中。 第一个想到的是TextPad(菜单:搜索/搜索文件)

第二个工具:UEStudio。

这些都是付费工具。 有试验,它们可以快速安装等。

如果做不到这一点,你可以安装Cygwin用于某些Linux风格的grepfunction。


问答问答

在这种情况下加载文件,将其拆分为“\ n”,保留一个计数器,并自己进行搜索 – 可能使用RegEx正则表达式。

…这里有一个很酷的LINQ表达式(你只需要where部分): Linq To Text Files

递归地使用目录类来捕获所有文件。

http://www.dotnetperls.com/recursively-find-files

您可能需要查看FINDSTR命令行实用程序: http ://technet.microsoft.com/en-us/library/bb490907.aspx

UltraEdit32是实现这一目标的更快捷/更简单的方法。 如果有大量的轮子,我认为你不需要重新制造轮子。

以下是我用来实现所需function的函数:

private void FindReferences( List output, string searchPath, string searchString ) { if ( Directory.Exists( searchPath ) ) { string[] files = Directory.GetFiles( searchPath, "*.*", SearchOption.AllDirectories ); string line; // Loop through all the files in the specified directory & in all sub-directories foreach ( string file in files ) { using ( StreamReader reader = new StreamReader( file ) ) { int lineNumber = 1; while ( ( line = reader.ReadLine() ) != null ) { if ( line.Contains( searchString, StringComparison.OrdinalIgnoreCase ) ) { output.Add( string.Format( "{0}:{1}", file, lineNumber ) ); } lineNumber++; } } } } } 

助手class:

 ///  /// Determines whether the source string contains the specified value. ///  /// The String to search. /// The search criteria. /// The string comparison options to use. ///  /// true if the source contains the specified value; otherwise, false. ///  public static bool Contains( this string source, string value, StringComparison comparisonOptions ) { return source.IndexOf( value, comparisonOptions ) >= 0; }