mirror of
https://github.com/lloeki/apply.git
synced 2025-12-06 09:24:38 +01:00
42 lines
885 B
Bash
Executable file
42 lines
885 B
Bash
Executable file
# 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"
|
|
}
|