如何从指定的文件中替换IP地址

时间:2017-03-21 11:56:32

标签: linux bash shell sed ip

我有以下脚本为此替换指定文件中的每个ip但逻辑错误

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

       i)
    echo "Proposed ip will $OPTARG"
    if [[ $OPTARG =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then

    sed -i 's/[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}$/'$OPTARG'/g' sample.txt 

    echo "proposed ip is $OPTARG"
    else
    echo "fail to update"
    fi ;;

       h) ;;
  esac
done

`

想要将所有搜索到的IP地址存储在数组中替换它我该怎么做

输入文件是

ome log file entries
some log file entries
some log file entries
some log file entries
This system ip is not found
some log file entries
some log file entries
some log file entries
This system IP is 122.0.0.0
some log file entries
some log file entries
This system IP:122.0.0.0
some log file entries
some log file entries
some log file entries
Hostname:ip-172.31.18.255.ec2.internal
some log file entries
some log file entries

1 个答案:

答案 0 :(得分:0)

以下解决方案允许您将所有匹配的IP地址存储在一个数组中,并在脚本的其他位置使用它们。根据我的观察(使用您的脚本),除了EC2专用主机名中包含的IP地址之外,源文件中的所有IP地址都被替换。目前尚不清楚这是不是你想要的。下面将替换所有IP地址(包括EC2主机名中包含的ip)。我正在使用的正则表达式取自已接受的答案in this post.

#!/usr/bin/env bash

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

declare ips=()
declare ip_regex='[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'
while getopts i:h: opt
do
   case $opt in

       i)
            echo "Proposed ip is $OPTARG"
            if [[ $OPTARG =~ ${regex} ]]; then
                # Store IPs in array for further processingg
                ips=$(echo $(cat "${DIR}/sample.txt") | grep -Eo ${ip_regex})

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

       h) ;;
  esac
done

如果您不想替换EC2主机名中包含的IP地址,那么正则表达式(我从this post的答案中构建的)如下所示应该可以正常工作

declare ip_regex='(^|[[:space:]])[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}([[:space:]]|$)'