更復雜的替換到檔案中?
我一直遇到這種型別的問題,但還沒有找到處理它的好方法。
我想將 gcache.size=3G 放入一個檔案中,需要根據情況替換或添加:
情況 1:附加到這一行
wsrep_provider_options="cert.optimistic_pa=no"
wsrep_provider_options="cert.optimistic_pa=no;gcache.size=3G;"
情況 2:追加但不放入 double ;;
wsrep_provider_options="cert.optimistic_pa=no;"
wsrep_provider_options="cert.optimistic_pa=no;gcache.size=3G;"
情況三:如果被注釋掉了,只需要添加一個我們想要設定的值的新行
#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;"
有沒有聰明的方法來做到這一點?
uj5u.com熱心網友回復:
要么您為此使用一些專用工具,例如 Ansible ( lineinfile ),要么您必須自己撰寫代碼。
#! /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
注意:SO 的語法高亮在很多情況下不起作用。他們不覺得對故障負責,因為突出顯示是由第三方工具完成的,他們對結果感到滿意。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/378769.html
標籤:猛击
