perl命令行替换

时间:2014-11-04 00:19:34

标签: regex perl command-line substitution

我有一个ips或主机名列表,我想将它们与我的数据库进行比较,我试图通过命令行进行操作,然后将其分解。

我的IP列表看起来像这样

10.0.0.1
10.1.1.1
10.2.2.2
hostname-as-12
... etc

我的数据库是这样的:

hostname:ip:location:contact

伪代码就像

open iplist
compare to database
replace inline iplist with new information

我想从命令行执行此操作(如果没有任何内容可以了解有关使用它的更多信息)

目前我的命令行如下所示:

perl -i.back -pe 's/^(.+)$/$1:`grep $1 /directory/tmp/datbase.txt` | cut -d : -f2`/' iplist

所以然后iplist会像这样改变

10.0.0.1:10.0.0.1
10.1.1.1:10.1.1.1
10.2.2.2:           #case not found
hostname-as-12:10.3.3.3

1 个答案:

答案 0 :(得分:0)

在命令行Perl中,您可以使用BEGIN块在开始时首先创建哈希。 File::Slurp模块为您提供了读取数据库文件的快捷方式。

额外的-l选项会在每次打印后添加换行符,以便您可以安全chomp输入&将它用作哈希键,而不必记住在输出中包含额外的换行符:

perl -i.back -MFile::Slurp -ple 'BEGIN { %db = map {m/^([^:]+):([^:]+)/; ($2 => $1)} read_file("/directory/tmp/database.txt") } chomp; $_ .= ":" . $db{$_} || ""' iplist

测试:

$ cat iplist
10.0.0.1
10.1.1.1
10.2.2.2
hostname-as-12
$ cat db.txt
10.0.0.1:10.0.0.1:foo:bar
10.1.1.1:10.1.1.1:foo:bar
10.3.3.3:hostname-as-12:foo:bar
$ perl -i.back -MFile::Slurp -ple 'BEGIN { %db = map {m/^([^:]+):([^:]+)/; ($2 => $1)} read_file("db.txt") } chomp; $_ .= ":" . $db{$_} || ""' iplist
$ cat iplist
10.0.0.1:10.0.0.1
10.1.1.1:10.1.1.1
10.2.2.2:
hostname-as-12:10.3.3.3
$

如果没有File::Slurp模块,您只需要在同一个BEGIN块中打开并读取文件,以填充%db哈希值。