// Original behavior/reference: sed (Lee E. McMahon) // Ported to .NET by Timothy J. Bruce namespace Icod.CoreUtils.Sed; using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Text.RegularExpressions; /// /// sed: stream editor (simplified). /// Supported features: /// -n suppress automatic printing /// -e script add script to the commands to run /// -i[SUFFIX] edit files in-place, optional backup SUFFIX (e.g. -i.bak or -i) /// -? display this help/usage text /// Script forms supported (subset): /// s/old/new/g substitute (supports regex) with optional g flag /// N i TEXT insert TEXT before line N (example: "1i this is foo") /// N r FILE read FILE and append its contents after line N (example: "2r file.txt") /// Multiple -e accepted; first script applied if none specified. /// This is a small, portable subset for common use cases. /// public static class Command { private sealed class Script { public enum KindT { Substitute, Insert, Read } public KindT Kind { get; } public string? Text { get; } public string? Pattern { get; } public string? Replacement { get; } public string? Flags { get; } public int LineNumber { get; } public string? FileName { get; } private Script( KindT k, string? text = null, string? pattern = null, string? replacement = null, string? flags = null, int lineNumber = 0, string? fileName = null ) { Kind = k; Text = text; Pattern = pattern; Replacement = replacement; Flags = flags; LineNumber = lineNumber; FileName = fileName; } public static Script Subst( string pattern, string replacement, string? flags ) => new Script( KindT.Substitute, pattern: pattern, replacement: replacement, flags: flags ); public static Script Insert( int lineNumber, string text ) => new Script( KindT.Insert, text: text, lineNumber: lineNumber ); public static Script Read( int lineNumber, string fileName ) => new Script( KindT.Read, lineNumber: lineNumber, fileName: fileName ); } public static int Run( string[] args, TextReader? stdin = null, TextWriter? stdout = null, TextWriter? stderr = null ) { stdin ??= Console.In; stdout ??= Console.Out; stderr ??= Console.Error; var scripts = new List