#!/bin/sh # Copyright (c) Victor Porton 2004. # Extreme Code Software (http://ex-code.com) - CHEAP custorm software. usage_msg="inplace [-v] [-i] [-n] [-s ] 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 " -i Interactively ask confirmation" echo " -n Don't backup" echo " -s Backup suffix (default .bak)" echo " -d 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.1 by Extreme Code (http://ex-code.com)."; exit 1; esac file="" suffix=".bak" backup=true confirm=false verbose=false diff="cmp -s" while test $# -gt 1; do case "$1" in -v) verbose=true ;; -i) confirm=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) if test $confirm = true; then overwrite="" while test -z $overwrite; do echo -n "Overwrite? "; read case $REPLY in y|Y|yes|true|t|T|Yes|True|YES|TRUE|1) overwrite=true;; n|N|no|false|f|F|No|False|NO|FALSE|0) overwrite=false;; esac done if test $overwrite = true; then mv "$OUT" "$IN" || rm "$OUT" # for the case of not writable $IN else rm "$OUT" fi else mv "$OUT" "$IN" || rm "$OUT" # for the case of not writable $IN fi ;; 2) echo "Can't compare files" >&2 exit 2 ;; esac