apply/lib
2021-07-11 15:27:30 -04:00

42 lines
885 B
Bash

# shellcheck shell=dash
# vim: ft=sh
# substitute replaces all occurances of one string with another in the provided
# file, writing to the specified output file.
substitute() {
local input="$1"
local output="$2"
shift 2
# TODO: real parsing
local search="$1"
local replace="$2"
#-v RS="$(printf "\0")" \
awk \
-v srch="$search" \
-v repl="$replace" \
-v RS="" \
-v ORS="" \
'{ gsub(srch, repl, $0); print $0 }' \
< "$input" > "$output"
}
# substituteInPlace works like substitute but operates in-place on the provided
# file
substituteInPlace() {
local fpath="$1"
shift
local tmpfile
tmpfile="$(mktemp)"
if ! substitute "$fpath" "$tmpfile" "$@"; then
rm "$tmpfile"
return $?
fi
# Overwrite now that we've succeeded
mv "$tmpfile" "$fpath"
}