Hi,

I think you should include this my script in GNU Core Utilities or an other
GNU package. Don't allow it to be lost as it is a very handy thing.

inplace --help

-- 
Victor Porton ([EMAIL PROTECTED])
 http://ex-code.com/~porton/bible/ - religious books etc.
#!/bin/sh

# Copyright (c) Victor Porton 2004.
# Extreme Code Software (http://ex-code.com) - CHEAP custorm software.

usage_msg="inplace [-v] [-n] [-s <suffix>] <file> cmd \$IN \$OUT"

function usage() {
    echo "$usage_msg"
    exit 1
}

function help() {
    echo "$usage_msg"
    echo
    echo "Performs inplace editing of a file."
    echo "  --help       Show help"
    echo "  --version    Show version info"
    echo "  -n           Don't backup"
    echo "  -s <suffix>  Backup suffix (default .bak)"
    echo "  -d <diffcmd> Command for comparison (default "cmp -s", can be e.g. \
"diff -u\")"
    echo "  -v           Be verbose"
    echo
    echo 'Example: inplace -v file.txt "sed -e s/John/Paul/g \$IN > \$OUT"'
    exit 0;
}

case "$1" in
    -h|--help) help;;
    --version) echo "inplace 0.9 by Extreme Code (http://ex-code.com)."; exit 1;
esac

file=""
suffix=".bak"
backup=true
verbose=false
diff="cmp -s"

while test $# -gt 1; do
    case "$1" in
        -v) verbose=true
            ;;
        -n) backup=false
            ;;
        -s) suffix="$2"; shift
            if test -z "$suffix"; then
                echo "Suffix can't be empty" >&2
                exit 1
            fi
            ;;
        -d) diff="$2"; shift
            if test -z "$diff"; then
                echo "Diff command can't be empty" >&2
                exit 1
            fi
            ;;
        -*) usage
            ;;
        *)  file="$1"; shift
            break
            ;;
    esac
    shift
done

if test -z "$file" || test $# -lt 1; then usage; fi

cmd=$@

IN="$file"
OUT=`tempfile -s .tmp`
if ! test -f "$IN"; then
    echo "File $IN doesn't exist!" >&2
    exit 2
fi
if test $backup = true; then
    cp "$IN" "$IN$suffix" || exit 2
fi
export IN OUT
#test $verbose = true && echo "$cmd"
if ! sh -c "$cmd"; then
    status=$?
    echo "** Command failed" >&2
    if test -f "$OUT"; then rm "$OUT"; fi
    exit 2
fi
if ! test -f "$OUT"; then
    echo "File $OUT isn't created!" >&2
    exit 2
fi
$diff -s "$IN" "$OUT"
case $? in
    0) if test verbose = true; then echo "No changes."; fi
       ;;
    1) mv "$OUT" "$IN" || rm "$OUT" # for the case of not writable $IN
       ;;
    2) echo "Can't compare files" >&2
       exit 2
       ;;
esac
_______________________________________________
Bug-coreutils mailing list
[EMAIL PROTECTED]
http://mail.gnu.org/mailman/listinfo/bug-coreutils

Reply via email to