diff --git a/README.md b/README.md index 038e31e..9d107c2 100644 --- a/README.md +++ b/README.md @@ -47,6 +47,8 @@ For something a bit more challenging, let's try counting the number of lines in numErrors, err := script.File("test.txt").Match("Error").CountLines() ``` +You can find a complete, runnable version of this in [examples/count_errors.go](examples/count_errors.go), along with other examples in the [`examples/`](examples) directory. + But what if, instead of reading a specific file, we want to simply pipe input into this program, and have it output only matching lines (like `grep`)? ```go diff --git a/examples/app.log b/examples/app.log new file mode 100644 index 0000000..8fcb66f --- /dev/null +++ b/examples/app.log @@ -0,0 +1,6 @@ +2026-06-19 12:00:00 [INFO] Starting application... +2026-06-19 12:01:05 [WARN] Low memory warning +2026-06-19 12:02:10 [ERROR] Database connection failed +2026-06-19 12:03:15 [INFO] Retrying database connection... +2026-06-19 12:04:20 [ERROR] Retries exhausted. Could not connect to database. +2026-06-19 12:05:00 [INFO] Shutting down application. diff --git a/examples/count_errors.go b/examples/count_errors.go new file mode 100644 index 0000000..91aa34c --- /dev/null +++ b/examples/count_errors.go @@ -0,0 +1,26 @@ +//go:build ignore + +// Counts the lines containing "ERROR" in a log file. +// +// Run it from the repository root: +// +// go run examples/count_errors.go +// +// Equivalent shell command: +// +// grep ERROR examples/app.log | wc -l +package main + +import ( + "fmt" + + "github.com/bitfield/script" +) + +func main() { + count, err := script.File("examples/app.log").Match("ERROR").CountLines() + if err != nil { + panic(err) + } + fmt.Printf("Number of ERROR lines: %d\n", count) +} diff --git a/examples/filter_csv.go b/examples/filter_csv.go new file mode 100644 index 0000000..f8a1ddc --- /dev/null +++ b/examples/filter_csv.go @@ -0,0 +1,25 @@ +//go:build ignore + +// Prints the names of servers whose status is "DOWN", read from a CSV file. +// +// Run it from the repository root: +// +// go run examples/filter_csv.go +// +// Equivalent shell command: +// +// grep DOWN examples/servers.csv | cut -d, -f1 +package main + +import ( + "github.com/bitfield/script" +) + +func main() { + // Column splits on whitespace, so turn the comma into a space first, + // then take the first field (the server name). + _, err := script.File("examples/servers.csv").Match("DOWN").Replace(",", " ").Column(1).Stdout() + if err != nil { + panic(err) + } +} diff --git a/examples/servers.csv b/examples/servers.csv new file mode 100644 index 0000000..e7a29ef --- /dev/null +++ b/examples/servers.csv @@ -0,0 +1,5 @@ +server1,UP +server2,DOWN +server3,DOWN +server4,UP +server5,DOWN