1

我是 Bash 脚本的新手,我需要一些帮助。

文件bbb.txt包含许多IPv4 和 IPv6 地址,如下所示:

10.0.2.15    fe80...
192.168.1.1   fe80...

文件aaa.txt有许多iptables 命令

我希望我的脚本在其中找到所有 IPv4 地址aaa.txt并检查它们是否可以在bbb.txt匹配时找到 - aaa.txt 中的 IPv4 被 bbb.txt 中的 IPv6 替换。可行吗?

4

2 回答 2

1

我认为你最好使用perl这个:

#!/usr/bin/perl

use strict;
use warnings;

my $file1 = 'aaa.txt';
my $file2 = 'bbb.txt';

open my $if1,'<',$file1 or die "$file1: $!\n";
open my $if2,'<',$file2 or die "$file2: $!\n";

my %ip_dictionary;
while(<$if2>){
    my ($ipv4,$ipv6)=split;
    $ip_dictionary{$ipv4}=$ipv6;
}
close $if2;

my $slurp = do { local $/; <$if1>};
close $if1;

$slurp=~ s!((?:[0-9]{1,3}\.){3}[0-9]{1,3})!exists $ip_dictionary{$1} and is_valid_ip($1) ? $ip_dictionary{$1} : $1!eg;

open my $of,'>',$file1;
print $of $slurp;

sub is_valid_ip{
    my $ip=shift//return 0;
    for(split /\./,$ip){
        return 0 if $_ > 255;
    }
    1
}
于 2013-09-08T20:53:12.857 回答
0

Save this to a file e.g. script.sh.

#!/bin/bash
declare -A A
while read -ra __; do
    A[${__[0]}]=${__[1]}
done < "$2"
while read -r __; do
    for I in "${!A[@]}"; do
        [[ $__ == *"$I"* ]] && {
            V=${A[$I}
            __=${__//"$I"/"$V"}
        }
    done
    echo "$__"
done < "$1"

Then run bash script.sh aaa.txt bbb.txt.

To get the output run it as something like bash script.sh aaa.txt bbb.txt > out.txt

I prefer to use Bash this time since you have to quote non-literals in Awk.

Another solution through Ruby:

ruby -e 'f = File.open(ARGV[0]).read; File.open(ARGV[1]).readlines.map{|l| l.split}.each{|a| f.gsub!(a[0], a[1])}; puts f' aaa.txt bbb.txt

Another way to modify file directly:

#!/bin/bash
A=$(<"$1")
while read -ra B; do
    A=${A//"${B[0]}"/"${B[1]}"}
done < "$2"
echo "$A" > "$1"

Run as bash script.sh aaa.txt bbb.txt.

Another through Ruby:

ruby -e 'x = File.read(ARGV[0]); File.open(ARGV[1]).readlines.map{|l| l.split}.each{|a| x.gsub!(a[0], a[1])}; File.write(ARGV[0], x)' aaa.txt bbb.txt
于 2013-09-08T20:39:23.850 回答