Skip to content

Instantly share code, notes, and snippets.

@onlytiancai
Created February 7, 2012 09:40
Show Gist options
  • Save onlytiancai/1758723 to your computer and use it in GitHub Desktop.
Save onlytiancai/1758723 to your computer and use it in GitHub Desktop.
linq版本grep
static void Main(string[] args)
{
if (args.Length != 2) return;
string searchPattern = args[0], dir = Path.GetDirectoryName(args[1]), filePattern = Path.GetFileName(args[1]);
var files = from file in Directory.EnumerateFiles(dir, filePattern, SearchOption.AllDirectories)
from line in File.ReadLines(file).Select((text, i) => new { Text = text, Index = i })
where new Regex(searchPattern).IsMatch(line.Text)
select new { File = file, LineText = line.Text, LineNo = line.Index };
Parallel.ForEach(files, (f) => { Console.WriteLine("{0}({1}){2}", f.File, f.LineNo, f.LineText); });
}
@LeoShi
Copy link

LeoShi commented Feb 7, 2012

private static void Main(string[] args)
        {
            if (args.Length != 2) return;
            Array.ForEach(Directory.EnumerateFiles(args[0]).ToArray(),
                          fileName =>
                              {
                                  var files = File.ReadLines(fileName).Select((line, index) => new {Text = line, Index = index})
                                      .Where(line => new Regex(args[1]).IsMatch(line.Text))
                                      .Select(line => new {FileName = fileName, Line = line.Text, LineNo = line.Index});
                                  Parallel.ForEach(files, f => Console.WriteLine("{0}({1}){2}", f.FileName, f.LineNo, f.Line));
                              });
        }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment