使用shell脚本更新配置文件
我有一个如下所示的配置文件:使用shell脚本更新配置文件,shell,unix,scripting,Shell,Unix,Scripting,我有一个如下所示的配置文件: define hostgroup { hostgroup_name NA-servers ; The name of the hostgroup alias NA region ; Long name of the group members sample.com ; hosts belonging to this group } define hostgroup{ hostgroup_name FTP-s
define hostgroup {
hostgroup_name NA-servers ; The name of the hostgroup
alias NA region ; Long name of the group
members sample.com ; hosts belonging to this group
}
define hostgroup{
hostgroup_name FTP-server ; The name of the hostgroup
alias FTP NA region ; Long name of the group
members example.com
}
我需要根据主机组名称有条件地更新成员
值
如何解析上述文件?此格式适用于基于正则表达式的解析:
#!/usr/bin/env bash
case $BASH_VERSION in ''|[1-3].*) echo "ERROR: Bash 4.0 or newer required" >&2; exit 1;; esac
PS4=':$LINENO+'; set -x # enable trace logging w/ line numbers
start_hostgroup_re='^define[[:space:]]+hostgroup[[:space:]]*[{]'
kv_re='^[[:space:]]*([^[:space:];]+)[[:space:]]+([^;]+)(;.*)?'
end_re='^[[:space:]]*}'
declare -A keys=( ) comments=( )
build_new_members() { # Replace this with your own code for generating a new member list
local hostgroup_name=$1 old_members=$2
echo "New member list for $hostgroup_name"
}
in_hostgroup=0
while IFS= read -r line; do : "line=$line"
if (( in_hostgroup )); then
if [[ $line =~ $kv_re ]]; then
keys[${BASH_REMATCH[1]}]=${BASH_REMATCH[2]}
comments[${BASH_REMATCH[1]}]=${BASH_REMATCH[3]}
elif [[ $line =~ $end_re ]]; then
keys["members"]=$(build_new_members "${keys["hostgroup_name"]}" "${keys["members"]}")
printf '%s\n' 'define hostgroup {'
for key in "${!keys[@]}"; do : key="$key"
value=${keys[$key]}
comment=${comments[$key]}
printf ' %-16s %s %s\n' "$key" "$value" "$comment"
done
printf '%s\n' '}'
keys=( ); comments=( ); in_hostgroup=0
elif [[ $line ]]; then # warn about non-empty non-assignment lines
printf 'WARNING: Unrecognized line in hostgroup: %s\n' "$line" >&2
fi
else
if [[ $line =~ $start_hostgroup_re ]]; then
in_hostgroup=1
else
printf '%s\n' "$line"
fi
fi
done
请参阅在以下位置运行的代码define hostgroup{hostgroup_name NA servers;主机组别名NA region的名称;组成员的长名称sample.com;属于此组的主机的逗号分隔列表}define hostgroup{hostgroup_name FTP server;主机组别名FTP NA区域的名称;组成员的长名称example.com}您是否有可靠的订购保证,或者您是否需要处理
成员
位于主机组名称
上方的定义?如果您没有关于输入的订购保证,在输出中对主机组内的密钥重新排序是否安全且可接受?顺序是有保证的。在主机组中的顺序始终相同。但是,随着更多这样的主机组被添加到该文件中,该文件将来可能会增长。遗憾的是,您没有预先指定这一点——我已经构建了一个不关心顺序的解决方案。也就是说,您应该能够使用它来获得灵感。