-
-
Save hoangitk/bb17391481a036a70dd5258c47384c01 to your computer and use it in GitHub Desktop.
LinqPad Find Text in File
This file contains hidden or 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
void Main() | |
{ | |
var searchWord = "TextToSearchFor"; | |
var searchPattern = "*.js"; | |
var sourceFolder = @"C:\_Dev\TFS\MyProject\Source\"; | |
var defaultProgram = @"C:\Program Files (x86)\Notepad++\notepad++.exe"; | |
List<string> allFiles = new List<string>(); | |
var fileCount = 0; | |
AddFileNamesToList(sourceFolder, allFiles, searchPattern); | |
$"Searching {allFiles.Count} Files With Pattern \"{searchPattern}\" For \"{searchWord}\"...".Dump(); | |
foreach (string fileName in allFiles) | |
{ | |
var dumpName = true; | |
var lineNum = 0; | |
foreach (var line in File.ReadLines(fileName)) | |
{ | |
lineNum++; | |
if(!line.Contains(searchWord)){ | |
continue; | |
} | |
if(dumpName){ | |
new Hyperlinq(() => { Process.Start(defaultProgram, fileName); }, fileName).Dump(); | |
dumpName = false; | |
fileCount++; | |
} | |
var trimmed = line.Trim(); | |
if (trimmed.Length > 150) | |
{ | |
trimmed = trimmed.Substring(0, 150); | |
} | |
($"{lineNum.ToString().PadLeft(4,'0')} - " + trimmed).Dump(); | |
} | |
if(!dumpName){ | |
"".Dump(); | |
} | |
} | |
$"{fileCount} Files found!".Dump(); | |
} | |
public static void AddFileNamesToList(string sourceDir, List<string> allFiles, string searchPattern) | |
{ | |
string[] fileEntries = Directory.GetFiles(sourceDir, searchPattern); | |
foreach (string fileName in fileEntries) | |
{ | |
allFiles.Add(fileName); | |
} | |
//Recursion | |
string[] subdirectoryEntries = Directory.GetDirectories(sourceDir); | |
foreach (string item in subdirectoryEntries) | |
{ | |
// Avoid "reparse points" | |
if ((File.GetAttributes(item) & FileAttributes.ReparsePoint) != FileAttributes.ReparsePoint) | |
{ | |
AddFileNamesToList(item, allFiles, searchPattern); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment