yunohost/data/helpers.d/string
2017-10-03 22:11:24 +02:00

37 lines
1.2 KiB
Text

# Generate a random string
#
# example: pwd=$(ynh_string_random 8)
#
# usage: ynh_string_random [length]
# | arg: length - the string length to generate (default: 24)
ynh_string_random() {
dd if=/dev/urandom bs=1 count=200 2> /dev/null \
| tr -c -d 'A-Za-z0-9' \
| sed -n 's/\(.\{'"${1:-24}"'\}\).*/\1/p'
}
# Substitute/replace a string by another in a file
#
# usage: ynh_replace_string match_string replace_string target_file
# | arg: match_string - String to be searched and replaced in the file
# | arg: replace_string - String that will replace matches
# | arg: target_file - File in which the string will be replaced.
ynh_replace_string () {
delimit=@
# Escape any backslash to preserve them as simple backslash.
match_string=${match_string//\\/"\\\\"}
replace_string=${replace_string//\\/"\\\\"}
# Escape the & character, who has a special function in sed.
match_string=${match_string//&/"\&"}
replace_string=${replace_string//&/"\&"}
# Escape the delimiter if it's in the string.
match_string=${1//${delimit}/"\\${delimit}"}
replace_string=${2//${delimit}/"\\${delimit}"}
workfile=$3
sudo sed --in-place "s${delimit}${match_string}${delimit}${replace_string}${delimit}g" "$workfile"
}