使用Shell脚本更新配置文件

时间:2018-06-27 11:40:47

标签: 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-server ; The name of the hostgroup
  alias           FTP NA region ; Long name of the group
  members         example.com
}

我需要根据members有条件地更新hostgroup_name值。

如何解析以上文件?

1 个答案:

答案 0 :(得分:1)

此格式适合基于正则表达式的解析:

#!/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

查看此代码在https://ideone.com/Z6kvcf上运行