forked from hetzneronline/installimage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtextprocessing.functions.sh
42 lines (34 loc) · 959 Bytes
/
textprocessing.functions.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#!/usr/bin/env bash
#
# textprocessing functions
#
# (c) 2016-2018, Hetzner Online GmbH
#
# safe_replace() <pattern> <replacement> <file>
# replace pattern with replacement if file exists and contains pattern
# $1 <pattern>
# $2 <replacement>
# $3 <file>
safe_replace() {
local pattern="${1}"
local replacement="${2}"
local file="${3}"
debug "# replacing ´${pattern}´ in file ${file}"
# check if file exists
if ! [[ -f "${file}" ]]; then
# report and fail if it does not
debug "file does not exist"
return 1
fi
# check if file contains pattern
if ! grep --extended-regexp --quiet "${pattern}" "${file}"; then
# report and fail if it does not
debug "pattern not found in file"
return 1
fi
# escape /
# bash builtins can not handle this!
replacement="$(echo "${replacement}" | sed 's/[\/&]/\\&/g')"
sed --regexp-extended --in-place "s/${pattern}/${replacement}/g" "${file}"
}
# vim: ai:ts=2:sw=2:et