替换一组文件中的文本字符串

时间:2015-10-02 13:23:43

标签: bash

我想知道Bash如何解决下一个练习。我在一个目录中有一组配置文件,其中指出了一些IP地址。 E.g:

public void DisplayPreBoundExceptions() { notifications.ForEach((t) => NotificationRequest.Raise(t)); notifications.Clear(); }

conf1.txt

ip-addr: 192.168.1.2; mask...; gateway...; another ip-addr: 192.168.1.5; one more ip-addr: 192.168.1.10; ...

conf2.txt

问题是:如何在所有文件中使用另一个IP地址池(192.168.1.100-192.168.1.254)更改所有IP地址。例如:

  • 192.168.1.2 - > 192.168.1.100
  • 192.168.1.5 - > 192.168.1.101
  • 192.168.1.10 - > 192.168.1.102

我认为有一些机制可以将值从一个数组分配给另一个数组,因为硬编码的版本如下:

ip-addr: 192.168.1.2;
mask...;
gateway...;
another ip-addr: 192.168.1.5;
one more ip-addr: 192.168.1.10;
...

不好。

3 个答案:

答案 0 :(得分:2)

也许略显冗长,但应该这样做。首先,将替换命令列表组合到一个临时文件中,然后执行sed以执行这些替换。

cmds=$(mktemp)
while read line
do
    printf "s/%s/%s/g\n" $line >> $cmds
done < ip_table

sed -f $cmds input > output
rm -f $cmds

这里,假设IP转换表存储在2列文件ip_table

192.168.1.2 192.168.1.100
192.168.1.5 192.168.1.101

虽然请注意,如果IP转换表看起来像

,这种方法可以解决它的问题
192.168.1.2 192.168.1.100
192.168.1.100 192.168.1.5

因为192.168.1.2被替换为192.168.1.5

答案 1 :(得分:1)

您想自动生成新IP吗?如果是这样,这是一种方法:

conf_files=config*.txt
pre=192.168.1.
suf=100

grep -hoP '([0-9]{1,3}\.){3}[0-9]{1,3}' $conf_files |
sort -u |
while read ip; do
    if (( suf > 254 )); then
        print "Error: Oops! Suffix is more than 254" >&2
        exit 1
    fi
    sed -i "s:$ip:$pre$suf:g" $conf_files
    ((suf++))
done

以下是它的工作原理:

  1. 从配置文件中提取所有IP地址
  2. 对它们进行排序并删除重复项
  3. 在while循环中,计算新IP和
  4. 使用sed替换旧IP

答案 2 :(得分:1)

硬编码的sed脚本不太好用。幸运的是,您可以动态创建一个sed脚本。

grep -ho '192\.168\.1\.[0-9]\+' conf*.txt \
    | sort | uniq | nl -v100 \
    | sed 's/\./\\./g;s/ *\(.*\)\t\(.*\)/s=\2=192.168.\1=g/' | LC_ALL=C sort \
    | sed -f- conf*.txt

第一行提取所有IP地址(请注意,其他方法表示如何表达它们)。

第二行抛出重复项,并从100开始编号。

第三行将每个以数字开头的IP地址更改为sed命令。然后对命令进行排序,以便在0.0.0.10之前替换0.0.0.100。

最后一行在输入文件上运行生成的脚本。

错误:不检查行数是否&lt; 157。

相关问题