#!/bin/sh -u # # Replace text between two lines denoted by regexps. # - Cameron Simpson 20sep95 # : ${TMPDIR:=/tmp} cmd=`basename "$0"` usage="Usage: $cmd -f from -t to [-i input] [-o output] replacement-files... -f from Start line marked specified by regexp \"from\". -t to Start line marked specified by regexp \"to\". -i input Take input from \"input\", default stdin. -o output Write result to \"output\", default stdout." input=- output=- from= to= badopts= while [ $# -gt 0 ] do case $1 in -f) from=$2; shift ;; -t) to=$2; shift ;; -i) input=$2; shift ;; -o) output=$2; shift ;; --) shift; break ;; -?*)echo "$cmd: unrecognised option: $1" >&2 badopts=1 ;; *) break ;; esac shift done [ -n "$from" ] || { echo "$cmd: missing -f option" >&2; badopts=1; } [ -n "$to" ] || { echo "$cmd: missing -t option" >&2; badopts=1; } [ $# = 0 ] && { echo "$cmd: missing replacement-files" >&2; badopts=1; } [ $badopts ] && { echo "$usage" >&2; exit 2; } tmp=$TMPDIR/$cmd.$$ front=$tmp.a back=$tmp.b case $from in */*) from=`printf '%s\n' "$from"|sed 's|/|\\\\/|g'` ;; esac case $to in */*) to=`printf '%s\n' "$to"|sed 's|/|\\\\/|g'` ;; esac ok=1 trap 'rm -f "$front" "$back"' 0 trap 'rm -f "$front" "$back"; exit 1' 1 2 13 15 exec 3<&0 # save stdin [ "x$input" = x- ] || exec <"$input" # read the whole input file and grab the top and bottom bits # this lets us use the same file for input and output sed -n "1,/$from/w $front /$to/,\$w $back" || ok= if [ $ok ] then [ "x$output" = x- ] || exec >"$output" for file in "$front" "$@" "$back" do case $file in -) cat <&3 ;; /*) cat "$file" ;; *) cat "./$file" ;; esac || ok= done fi [ $ok ] && exit 0 exit 1