Created
September 16, 2017 02:09
-
-
Save jpdillingham/b192ca71ab2aee449331437aee4a64d0 to your computer and use it in GitHub Desktop.
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
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
using System.Text.RegularExpressions; | |
using System.IO; | |
namespace grep | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
string joinedArgs = String.Join(" ", args); | |
string[] splitArgs = joinedArgs.Split(';'); | |
List<string> lines = new List<string>(); | |
List<string> matchedLines = new List<string>(); | |
if (splitArgs.Length != 2) | |
{ | |
Console.WriteLine("Invalid parameters. Syntax: grep.exe pattern; file"); | |
return; | |
} | |
string pattern = splitArgs[0]; | |
string file = splitArgs[1]; | |
if (!File.Exists(file)) | |
{ | |
Console.WriteLine("Unable to find file '" + file + "'."); | |
return; | |
} | |
lines = File.ReadAllLines(file).ToList<string>(); | |
matchedLines = GetMatchingLines(pattern, lines); | |
foreach(string line in matchedLines) | |
{ | |
Console.WriteLine(line); | |
} | |
Console.WriteLine("Found " + matchedLines.Count + " matching lines."); | |
} | |
/// <summary> | |
/// Returns a string array containing the lines matching the provided wildcard in the provided string array | |
/// </summary> | |
/// <returns></returns> | |
static List<string> GetMatchingLines(string wildcard, List<string> lines) | |
{ | |
string pattern = WildcardToRegex(wildcard); | |
List<string> retVal = new List<string>(); | |
foreach (string line in lines) | |
{ | |
if (Regex.IsMatch(line, pattern)) | |
retVal.Add(line); | |
} | |
return retVal; | |
} | |
/// <summary> | |
/// Converts the specified wildcard pattern to a regular expression. | |
/// </summary> | |
/// <param name="pattern">The wildcard pattern to convert.</param> | |
/// <returns>The regular expression resulting from the conversion.</returns> | |
internal static string WildcardToRegex(string pattern = "") | |
{ | |
return "^" + System.Text.RegularExpressions.Regex.Escape(pattern) | |
.Replace(@"\*", ".*") | |
.Replace(@"\?", ".") | |
+ "$"; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment