想要替换主机名但正则表达式不匹配模式

时间:2017-03-22 07:13:13

标签: bash shell replace hostname

我的代码是

#!/usr/bin/env bash

#
# Directory where this script is located
#
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

declare hosts=()

#declare host_regex='[01]?[0-9][0-9]?|2[0-4][0-9]|25[0-5])(\.([01]?[0-9][0-9]?|2[0-4][0-9]|25[0-5])){3}'

declare host_regex = '^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$'

#declare host_regex='(?=^.{4,253}$)(^((?!-)[a-zA-Z0-9-]{1,63}(?<!-)\.)+[a-zA-Z]{2,63})$'

while getopts i:h: opt
do
   case $opt in

       i)

     ;;

       h) 
      echo "Proposed Hostname $OPTARG"
      if [[ $OPTARG =~ ${host_regex} ]]; then
                # Store Hostname in array for further processingg
                hosts=$(echo $(cat "${DIR}/sample.txt") | grep -Eo ${host_regex})

                for host in ${hosts[@]}; do
                    echo "Replacing '${host}' with '${OPTARG}'"
                    sed -e 's/'${host}'/'$OPTARG'/g' "${DIR}/sample.txt"
                done
            else
                echo "Failed to update hostname"
            fi

     ;;
  esac
done

我已尝试使用以下代码替换主机名,但正则表达式与模式不匹配。 我已经尝试了我的代码中指定的所有这个正则表达式以及注释的正则表达式

0 个答案:

没有答案