Xah Talk Show 2021-11-09 WolframLang tutorial, on writing a grep, live coding

Xah Talk Show 2021-11-09 WolframLang tutorial, on writing a grep, live coding

WolframLang code to grep files in a dir:

#!/usr/bin/env wolframscript

executable = $ScriptCommandLine[[1]]

If[Length[$ScriptCommandLine] != 3,
  Print["USAGE:"]
  Print[executable, " PATTERN PATH"]
  Exit[1]
]

pattern = $ScriptCommandLine[[2]]
path = $ScriptCommandLine[[3]]

addIndices[list_] := MapIndexed[{First[#2], #1}&, list]
lines[text_] := StringSplit[text, {"\r\n", "\r", "\n"}] // addIndices
matchingLines[text_] := Select[lines[text], StringContainsQ[#[[2]], pattern]&]
printLine[{number_, contents_}] := Print[number, "\t", contents]

printIfMatch[file_] :=
  With[{contents = ReadString[file]},
    If[StringContainsQ[contents, pattern],
      Print[file]
      Scan[printLine, matchingLines[contents]]
      Print[]
    ]
  ]

FileSystemScan[printIfMatch, path]

Slight improvement:

(*
give a dir path, and a string pattern,
open every file in the dir.
if the file content contains the pattern,
print the line that occure, and print a line number in front
*)

If[
 Length[$ScriptCommandLine] != 3,
  Print["USAGE:"];
  Print[$ScriptCommandLine[[1]], " PATTERN PATH"];
  Exit[1]
]

pattern = $ScriptCommandLine[[2]]
path = $ScriptCommandLine[[3]]

addIndices = Function[{list}, MapIndexed[ Function[{x,y}, {First[y], x }] , list] ]

lines = addIndices[StringSplit[#, {"\r\n", "\r", "\n"}] ]&

matchingLines = Function[{text} , Select[ lines[text], StringContainsQ[#[[2]], pattern]& ] ]

printLine = Function[{x} , Print[x[[1]], "\t", x[[2]] ]]

printIfMatch = Function[{file}, With[{contents = ReadString[file]}, If[StringContainsQ[contents, pattern], Print[file]; Scan[printLine, matchingLines[contents]]; Print[]; ] ] ]

FileSystemScan[printIfMatch, path]
WolframLang 2021-11-09 S65M
WolframLang 2021-11-09 S65M
WolframScript 2021-11-09 WRxP
WolframScript 2021-11-09 WRxP

xah_talk_show_2021-11-09.txt