goawk: github.com/benhoyt/goawk/interp Index | Examples | Files

package interp

import "github.com/benhoyt/goawk/interp"

Package interp is the GoAWK interpreter (a simple tree-walker).

For basic usage, use the Exec function. For more complicated use cases and configuration options, first use the parser package to parse the AWK source, and then use ExecProgram to execute it with a specific configuration.

Code:

input := bytes.NewReader([]byte("foo bar\n\nbaz buz"))
err := interp.Exec("$0 { print $1 }", " ", input, nil)
if err != nil {
    fmt.Println(err)
    return
}

Output:

foo
baz

Code:

// Use ',' as the field separator
input := bytes.NewReader([]byte("1,2\n3,4"))
err := interp.Exec("{ print $1, $2 }", ",", input, nil)
if err != nil {
    fmt.Println(err)
    return
}

Output:

1 2
3 4

Code:

src := `BEGIN { print sum(), sum(1), sum(2, 3, 4), repeat("xyz", 3) }`

parserConfig := &parser.ParserConfig{
    Funcs: map[string]interface{}{
        "sum": func(args ...float64) float64 {
            sum := 0.0
            for _, a := range args {
                sum += a
            }
            return sum
        },
        "repeat": strings.Repeat,
    },
}
prog, err := parser.ParseProgram([]byte(src), parserConfig)
if err != nil {
    fmt.Println(err)
    return
}
interpConfig := &interp.Config{
    Funcs: parserConfig.Funcs,
}
_, err = interp.ExecProgram(prog, interpConfig)
if err != nil {
    fmt.Println(err)
    return
}

Output:

0 1 9 xyzxyzxyz

Code:

src := "{ print NR, tolower($0) }"
input := "A\naB\nAbC"

prog, err := parser.ParseProgram([]byte(src), nil)
if err != nil {
    fmt.Println(err)
    return
}
config := &interp.Config{
    Stdin: bytes.NewReader([]byte(input)),
    Vars:  []string{"OFS", ":"},
}
_, err = interp.ExecProgram(prog, config)
if err != nil {
    fmt.Println(err)
    return
}

Output:

1:a
2:ab
3:abc

Index

Examples

Package Files

functions.go interp.go io.go value.go

func Exec Uses

func Exec(source, fieldSep string, input io.Reader, output io.Writer) error

Exec provides a simple way to parse and execute an AWK program with the given field separator. Exec reads input from the given reader (nil means use os.Stdin) and writes output to stdout (nil means use a buffered version of os.Stdout).

func ExecProgram Uses

func ExecProgram(program *Program, config *Config) (int, error)

ExecProgram executes the parsed program using the given interpreter config, returning the exit status code of the program. Error is nil on successful execution of the program, even if the program returns a non-zero status code.

type Config Uses

type Config struct {
    // Standard input reader (defaults to os.Stdin)
    Stdin io.Reader

    // Writer for normal output (defaults to a buffered version of
    // os.Stdout)
    Output io.Writer

    // Writer for non-fatal error messages (defaults to a buffered
    // version of os.Stderr)
    Error io.Writer

    // The name of the executable (accessible via ARGV[0])
    Argv0 string

    // Input arguments (usually filenames): empty slice means read
    // only from Stdin, and a filename of "-" means read from Stdin
    // instead of a real file.
    Args []string

    // List of name-value pairs for variables to set before executing
    // the program (useful for setting FS and other built-in
    // variables, for example []string{"FS", ",", "OFS", ","}).
    Vars []string

    // Map of named Go functions to allow calling from AWK. You need
    // to pass this same map to the parser.ParseProgram config.
    //
    // Functions can have any number of parameters, and variadic
    // functions are supported. Functions can have no return values,
    // one return value, or two return values (result, error). In the
    // two-value case, if the function returns a non-nil error,
    // program execution will stop and ExecProgram will return that
    // error.
    //
    // Apart from the error return value, the types supported are
    // bool, integer and floating point types (excluding complex),
    // and string types (string or []byte).
    //
    // It's not an error to call a Go function from AWK with fewer
    // arguments than it has parameters in Go. In this case, the zero
    // value will be used for any additional parameters. However, it
    // is a parse error to call a non-variadic function from AWK with
    // more arguments than it has parameters in Go.
    //
    // Functions defined with the "function" keyword in AWK code
    // take precedence over functions in Funcs.
    Funcs map[string]interface{}

    // Set one or more of these to true to prevent unsafe behaviours,
    // useful when executing untrusted scripts:
    //
    // * NoExec prevents system calls via system() or pipe operator
    // * NoFileWrites prevents writing to files via '>' or '>>'
    // * NoFileReads prevents reading from files via getline or the
    //   filenames in Args
    NoExec       bool
    NoFileWrites bool
    NoFileReads  bool
}

Config defines the interpreter configuration for ExecProgram.

type Error Uses

type Error struct {
    // contains filtered or unexported fields
}

Error (actually *Error) is returned by Exec and Eval functions on interpreter error, for example a negative field index.

func (*Error) Error Uses

func (e *Error) Error() string

Package interp imports 23 packages (graph) and is imported by 3 packages. Updated 2019-05-30. Refresh now. Tools for package owners.