更复杂的替换为文件?
我经常遇到这样的问题,却没有找到一个很好的方法来处理它。
我想将gcache.size=3G放到一个文件中,它需要根据情况替换或添加:
情境1:附加到本行
wsrep_provider_options="cert.optimistic_pa=no"
wsrep_provider_options="cert.optimistic_pa=no;gcache.size=3G;"情境2:附加但不加双;
wsrep_provider_options="cert.optimistic_pa=no;"
wsrep_provider_options="cert.optimistic_pa=no;gcache.size=3G;"情况3:如果注释掉了,只需添加一个新行,其中包含我们希望设置的值。
#wsrep_provider_options="cert.optimistic_pa=no"
wsrep_provider_options="gcache.size=3G"情境4:如果不存在,就添加它
<line doesn't exist>
wsrep_provider_options="gcache.size=3G"情况5:如果它是一个不同的值,替换
wsrep_provider_options="cert.optimistic_pa=no;gcache.size=5G;"
wsrep_provider_options="cert.optimistic_pa=no;gcache.size=3G;"有什么聪明的办法吗?
发布于 2021-12-08 12:05:22
要么使用一些专用工具,比如Ansible (线状),要么自己编写代码。
#! /bin/bash
override ()
{
local var_is_set=false
local opt_is_set
local -a options
local option
while read -r line; do
echo "line: $line" >&2
if [[ $line =~ ^(.?)wsrep_provider_options=\"(.*)\" ]]; then
var_is_set=true
if [[ "${BASH_REMATCH[1]}" == '#' ]]; then
printf '%s\n' "$line" 'wsrep_provider_options="gcache.size=3G"'
else
printf 'wsrep_provider_options="'
IFS=';' read -ra options <<< "${BASH_REMATCH[2]}"
opt_is_set=false
for option in "${options[@]}"; do
if [[ $option =~ ^gcache\.size= ]]; then
opt_is_set=true
printf 'gcache.size=3G;'
else
printf 'option ##%s##\n' "$option" >&2
if [[ $option ]]; then
printf '%s;' "$option"
fi
fi
done
if [[ $opt_is_set == false ]]; then
printf "gcache.size=3G;"
fi
printf '"\n'
fi
else
printf '%s\n' "$line"
fi
done
if [[ $var_is_set == false ]]; then
printf '%s\n' 'wsrep_provider_options="gcache.size=3G"'
fi
}
testcase=()
testdata=()
testcase+=('Situation 1: Append to this line')
testdata+=('wsrep_provider_options="cert.optimistic_pa=no"')
testcase+=('Situation 2: append but don'\''t put in double ;;')
testdata+=('wsrep_provider_options="cert.optimistic_pa=no;"')
testcase+=('Situation 3: If commented out, just add a new line with the value we want set')
testdata+=('#wsrep_provider_options="cert.optimistic_pa=no"')
testcase+=('Situation 4: If doesn'\''t exist, add it')
testdata+=('')
testcase+=('Situation 5: if it'\''s a different value, replace')
testdata+=('wsrep_provider_options="cert.optimistic_pa=no;gcache.size=5G;"')
for ((i=0 ; i < "${#testcase[@]}" ; i++)); do
printf "$(tput bold)%s$(tput sgr0)\n" "${testcase[$i]}"
printf 'Input:\n%s\n' "${testdata[$i]}"
printf 'Output:\n%s\n' "$(override <<< "${testdata[$i]}")"
printf '\n'
done注意:https://meta.stackoverflow.com/q/412191/402322。他们不觉得对故障负责,因为高亮是由第三方工具完成的,他们对结果很满意。
https://stackoverflow.com/questions/70267672
复制相似问题