sed
sed is a stream editor for filtering and transforming text.
This module constructs
ward.process.cmd(...)invocations; it does not parse output. consumers can usewardlib.tools.out(or their own parsing) on the:output()result.
Import
local Sed = require("wardlib.app.sed").Sed
Portability notes
-E(extended regex) is supported on both GNU and BSD sed.- In-place editing (
-i) differs between implementations. This wrapper modelsin_placeso it works on GNU sed and is typically accepted on BSD sed as well. If you need strict BSD behavior, passextra = { "-i", ".bak" }.
API
Sed.bin
Executable name or path (default: "sed").
Sed.run(inputs, opts)
Builds: sed <opts...> [inputs...]
- If
inputsisnil, sed reads stdin. inputsacceptsstring|string[]|nil.
Sed.script(script, inputs, opts)
Convenience wrapper around Sed.run that adds -e <script>.
Sed.replace(pattern, repl, inputs, opts)
Convenience wrapper that adds -e s/pattern/repl/g.
This does not escape
pattern/repl; escape them yourself if needed.
Sed.inplace_replace(pattern, repl, inputs, backup_suffix, opts)
Convenience wrapper that enables in-place editing (via -i) and adds the substitution.
inputsmust bestring|string[](a real file path list).backup_suffixmay benil(GNU-style-i) or a string like.bak.
Options
SedOpts
extended: boolean?→-Equiet: boolean?→-nin_place: boolean|string?→-ior-i<suffix>backup_suffix: string?→ alias forin_place = "<suffix>"expression: string|string[]?→-e <script>(repeatable)file: string|string[]?→-f <file>(repeatable)null_data: boolean?→-z(GNU)follow_symlinks: boolean?→--follow-symlinks(GNU)posix: boolean?→--posix(GNU)sandbox: boolean?→--sandbox(GNU)extra: string[]?→ extra argv appended after modeled options
Examples
Apply a script to stdin
local Sed = require("wardlib.app.sed").Sed
-- sed -e 's/foo/bar/g'
local cmd = Sed.script("s/foo/bar/g")
Apply a script to files
local Sed = require("wardlib.app.sed").Sed
-- sed -E -e 's/foo/bar/g' a.txt b.txt
local cmd = Sed.replace("foo", "bar", { "a.txt", "b.txt" }, { extended = true })
In-place edit
local Sed = require("wardlib.app.sed").Sed
-- sed -i.bak -e 's/hello/hi/g' file.txt
local cmd = Sed.inplace_replace("hello", "hi", "file.txt", ".bak")
cmd:run()
Multiple expressions
local Sed = require("wardlib.app.sed").Sed
-- sed -e 's/a/b/g' -e 's/c/d/g' file.txt
local cmd = Sed.run("file.txt", {
expression = { "s/a/b/g", "s/c/d/g" },
})
Read stdout using wardlib.tools.out
local Sed = require("wardlib.app.sed").Sed
local out = require("wardlib.tools.out")
local txt = out.cmd(Sed.script("s/foo/bar/g"))
:label("sed")
:text()