ambevar-dotfiles/.scripts/replace

61 lines
1.2 KiB
Plaintext
Raw Normal View History

2014-01-06 11:25:21 +01:00
#!/bin/sh
_printhelp ()
{
cat<<EOF
Usage: ${1##*/} [OPTIONS] SEARCH REPLACE [FILES]
2014-01-06 11:25:21 +01:00
Replace SEARCH by REPLACE in FILES. If no file is provided, use stdin.
Backslashes are interpreted in SEARCH and REPLACE (e.g. \n, \t). If you want to
2014-01-06 15:24:31 +01:00
inhibit this behaviour, you need to double them.
2014-01-06 11:25:21 +01:00
Options:
-h: Show this help.
-i: Replace file content instead of printing to stdout.
2014-01-06 11:25:21 +01:00
EOF
}
OPT_INPLACE=""
while getopts ":ih" opt; do
case $opt in
i)
OPT_INPLACE=-i ;;
h)
_printhelp "$0"
exit 1 ;;
?)
_printhelp "$0"
exit 1 ;;
esac
done
shift $(($OPTIND - 1))
if [ $# -lt 2 ]; then
_printhelp "$0"
exit 1
fi
search="$1"
replace="$2"
shift 2
_replace()
{
## We cannot use gsub, otherwise regex substitutions could occur.
## Source: http://mywiki.wooledge.org/BashFAQ/021
awk -v s="$search" -v r="$replace" 'BEGIN {l=length(s)} {o="";while (i=index($0, s)) {o=o substr($0,1,i-1) r; $0=substr($0,i+l)} print o $0}' "$@"
2014-01-06 11:25:21 +01:00
}
if [ $# -eq 0 ] || [ -z "$OPT_INPLACE" ]; then
_replace "$@"
else
for i ; do
out="$(mktemp "$i.XXXXXX")"
_replace "$i" > "$out"
mv "$out" "$i"
done
fi