Created
February 5, 2012 03:53
-
-
Save onlytiancai/1742527 to your computer and use it in GitHub Desktop.
紧凑版的grep
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
紧凑版的grep,相对于对象健身操的实现,这段代码只是原版本的三分之一,个人感觉可读性也不是太差。 | |
原文地址:https://gist.github.com/1738383 | |
*/ | |
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text.RegularExpressions; | |
using System.IO; | |
using System.Threading.Tasks; | |
namespace Gerp2 | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
if (args.Length != 2) | |
{ | |
Console.WriteLine("Usage:grep <searchPattern> <filePattern>"); | |
Console.WriteLine(@"Example: grep \d+ d:\code\*.py"); | |
return; | |
} | |
string searchPattern = args[0], filePath = args[1], | |
dirName = Path.GetDirectoryName(filePath), filePattern = Path.GetFileName(filePath); | |
DirectoryInfo dir = new DirectoryInfo(string.IsNullOrEmpty(dirName) ? Directory.GetCurrentDirectory() : dirName); | |
Regex searchRegex = new Regex(searchPattern, RegexOptions.IgnoreCase); | |
var files = GetFiles(filePattern, dir); | |
Parallel.ForEach(files, file => { | |
Grep(file, searchRegex); | |
}); | |
} | |
static IEnumerable<FileInfo> GetFiles(string filePattern, DirectoryInfo currentDir) | |
{ | |
var currentDirFiles = currentDir.GetFiles(filePattern); | |
foreach (FileInfo file in currentDirFiles) | |
{ | |
yield return file; | |
} | |
var subDirs = currentDir.GetDirectories(); | |
foreach (var subDir in subDirs) | |
{ | |
var subDirFiles = GetFiles(filePattern, subDir); | |
foreach (var file in subDirFiles) | |
{ | |
yield return file; | |
} | |
} | |
} | |
static void Grep(FileInfo file, Regex searchRegex) | |
{ | |
using (StreamReader reader = new StreamReader(file.FullName)) | |
{ | |
int lineNo = 0; | |
while (true) | |
{ | |
string line = reader.ReadLine(); | |
if (line == null) | |
return; | |
lineNo++; | |
if (!searchRegex.IsMatch(line)) | |
continue; | |
Console.WriteLine("{0}({1}):{2}", file.FullName, lineNo, line); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment