Last active
August 8, 2026 11:17
-
-
Save brianmed/79323786655c8d7373978fc14549e5f2 to your computer and use it in GitHub Desktop.
stream is a utility that is a line oriented find and replace using C# Regular Expressions
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
| #!/usr/bin/env -S dotnet -- | |
| // 1) Install dotnet sdk, e.g., sudo apt install dotnet-sdk-10.0 | |
| // 2) Copy gist to stream.cs | |
| // 3) chmod a+x stream.cs | |
| // 4) ./stream.cs -e 's#Joy#Wawa#' | |
| using System.Text.RegularExpressions; | |
| if (args.Length == 0 || args.Contains("--help")) | |
| { | |
| Console.WriteLine(@"Description: | |
| Process regular expression(s) over lines in a file. | |
| Usage: | |
| stream [options] | |
| Options: | |
| -e A regular expression. | |
| -f A file with regular expressions. | |
| --help Display this help."); | |
| Environment.Exit(0); | |
| } | |
| // TODO: Class | |
| List<Regex> RegexesFind = new(); | |
| List<string> RegexesReplace = new(); | |
| List<bool> RegexesReplaceAll = new(); | |
| foreach (string regex in GetRegexes(args)) | |
| { | |
| char splitOn = regex[1]; | |
| RegexesFind.Add(new Regex(regex.Split(splitOn)[1], RegexOptions.None)); | |
| RegexesReplace.Add(regex.Split(splitOn)[^2]); | |
| RegexesReplaceAll.Add(regex.ToLower().EndsWith('g')); | |
| } | |
| using (StreamReader stdin = new(Console.OpenStandardInput())) | |
| { | |
| while (stdin.ReadLine() is string line) | |
| { | |
| foreach ((int index, Regex regex) in RegexesFind.Index()) | |
| { | |
| line = regex.Replace(line, RegexesReplace[index], RegexesReplaceAll[index] ? Int32.MaxValue : 1); | |
| } | |
| Console.WriteLine(line); | |
| } | |
| } | |
| IEnumerable<string> GetRegexes(string[] args) | |
| { | |
| bool prevDashE = false; | |
| bool prevDashF = false; | |
| foreach (string arg in args) | |
| { | |
| if (prevDashE) | |
| { | |
| prevDashE = false; | |
| yield return arg; | |
| } | |
| else if (prevDashF) | |
| { | |
| using (StreamReader stdin = new(File.OpenRead(arg))) | |
| { | |
| while (stdin.ReadLine() is string line) | |
| { | |
| yield return line; | |
| } | |
| } | |
| } | |
| else if (arg.Equals("-e")) | |
| { | |
| prevDashE = true; | |
| } | |
| else if (arg.Equals("-f")) | |
| { | |
| prevDashF = true; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment