night/regex/env-fixed.sed

52 lines
2.1 KiB
Sed

# Fixed environment access and mutation using regular expressions
#
# Copyright (C) 2018 Mike Gerwitz
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# This is a fairly simply example demonstrating how an environment
# consisting of pre-determined variables can be accessed and manipulated
# using only regular expressions (in the formal sense).
#
# See also `env-dyn.sed' for a a much more sophisticated example of a
# dynamic environment where the variables are _not_ pre-determined.
##
# Read all lines into the pattern space.
:a; N; $!ba
# Variable reference in an assignment form. This copies the value from the
# environment line into the assignment line. Note that this will only
# perform a single replacement per variable. Because regexes are greedy,
# this will replace the _last_ occurrence in the assignment form with the
# value of the current environment.
s/\(x=\)\([^ ]*\)\(.*\n.<-.*\)x/\1\2\3\2/
s/\(y=\)\([^ ]*\)\(.*\n.<-.*\)y/\1\2\3\2/
s/\(z=\)\([^ ]*\)\(.*\n.<-.*\)z/\1\2\3\2/
# Environment mutation. This assigns a new value to the environment by
# copying the value from the assignment line into the environment line.
s/\(x=\)[^ ]*\(.*\)\nx<-\([^ ]*\)/\1\3\2/
s/\(y=\)[^ ]*\(.*\)\ny<-\([^ ]*\)/\1\3\2/
s/\(z=\)[^ ]*\(.*\)\nz<-\([^ ]*\)/\1\3\2/
# The above expressions should have eliminated the assignment line if there
# was a match; if it still exists, then there is a syntax error.
s/.<-.*$/ERROR: &/
# This script only handles a single pass. Let the animate script know that
# we are done.
q1