使用sed将链接替换为html链接

时间:2013-12-30 16:52:51

标签: regex bash sed

好的,我在文件中有一堆IP,我希望使用sed来附加前缀和后缀。

例如,我有

http://profile/userA
1.2.3.4
http://profile/userB
2.2.3.4
http://profile/userC
3.2.3.4
http://profile/userD
4.2.3.4

我如何在bash中对其进行编码,以便sed将用

之类的内容替换所有IP
<a href="http://www.ip-tracker.org/locator/ip-lookup.php?ip=1.2.3.4">1.2.3.4</a>
<a href="http://www.ip-tracker.org/locator/ip-lookup.php?ip=2.2.3.4">2.2.3.4</a>
<a href="http://www.ip-tracker.org/locator/ip-lookup.php?ip=3.2.3.4">3.2.3.4</a>
<a href="http://www.ip-tracker.org/locator/ip-lookup.php?ip=4.2.3.4">4.2.3.4</a>

此?

4 个答案:

答案 0 :(得分:2)

我会尝试这样的事情:

sed 's@.*@<a href="http://www.ip-tracker.org/locator/ip-lookup.php?ip=&">&</a>@' /tmp/ips

答案 1 :(得分:0)

这是一个选项:

sed 's%^\([0-9.]*\)$%<a href="http://www.ip-tracker.org/locator/ip-lookup.php?ip=\1">\1</a>%'

请注意,此处使用正则表达式[0-9.]*以简洁的方式匹配IP地址,但它假定您已经在验证IP地址在其他位置是否有效。以下页面为正则表达式提供了一个很好的示例,它只匹配有效的IP地址,但您可能需要使其适应sed:
http://www.regular-expressions.info/examples.html

答案 2 :(得分:0)

sed -e 's/^([0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3})/aaa\1 bbb/' InputFile

将在您的IP地址前加上aaa并附加bbb。

在下面的@sudo_O评论之后添加,这实际上不是所要求的。

鉴于文件:

1.2.3.4
2.2.3.4
3.2.3.4
4.2.3.4
192.168.0.54
1192.168.0.54
 Opps some text 192.168.0.54 on this line.

然后

sed -e 's@[\s]*([0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3})@\1@' InputFile

给你,

<a href="http://www.ip-tracker.org/locator/ip-lookup.php?ip=1.2.3.4">1.2.3.4</a>
<a href="http://www.ip-tracker.org/locator/ip-lookup.php?ip=2.2.3.4">2.2.3.4</a>
<a href="http://www.ip-tracker.org/locator/ip-lookup.php?ip=3.2.3.4">3.2.3.4</a>
<a href="http://www.ip-tracker.org/locator/ip-lookup.php?ip=4.2.3.4">4.2.3.4</a>
<a href="http://www.ip-tracker.org/locator/ip-lookup.php?ip=192.168.0.54">192.168.0.54</a>
1<a href="http://www.ip-tracker.org/locator/ip-lookup.php?ip=192.168.0.54">192.168.0.54</a>
 Opps some text <a href="http://www.ip-tracker.org/locator/ip-lookup.php?ip=192.168.0.54">192.168.0.54</a> on this line.

我最初没有给你第二个解决方案,因为我试着让正则表达式更容易理解,但是自从得到评论后我想我应该再试一次。

请注意,无效的IP不会被转换,也不会假设IP在一条线上是单独的

答案 3 :(得分:0)

你可以尝试:

awk 'NR%2==0 {
    print "<a href=\"http://www.ip-tracker.org/locator/ip-lookup.php?ip="$1"\">"$1"</a>"
}' file