2010-12-20 47 views
6

Greetz人。Shell相当于PHP的preg_replace()

我正在寻找一种方法来执行相同的东西,而不是PHP的preg_replace()(在shell脚本中搜索与正则表达式匹配的文本并替换它)。

因此,请考虑以下文件。

<a href="http://example.com/">Website #1</a> 
<a href="http://example.net/">Website #2</a> 
<a href="http://example.org/">Website #3</a> 

而且我要得到这个:

http://example.com/ 
http://example.net/ 
http://example.org/ 

有没有办法做到这一点?谢谢。

+0

您的文字从你的例子不同。你想提取你的字符串的一部分(如你的例子)还是你想实际取代它? – plundra 2010-12-20 15:18:19

+1

此外,[不要使用正则表达式解析HTML](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454)(in一般)。 – delnan 2010-12-20 15:19:11

+0

如果你说,“所以,考虑下面的文件。”,那么人们会认为这是数据。下次做个正确的问题。 – Anders 2010-12-20 15:20:15

回答

9

您可以使用sed为:

sed -r 's/.*href="([^"]*)".*/\1/' file 

See it

+0

太好了,谢谢!所以我假设'''是告诉sed使用正则表达式,但'\ 1 /'是什么? – seriousdev 2010-12-20 15:26:25

+0

不,'s'是替代品,'\ 1'是第一个匹配(组?不确定这个词),1是第一个括号的内容。 '[^“] *'在上述情况下。 – plundra 2010-12-20 15:32:46

+0

@plundra谢谢。 – seriousdev 2010-12-20 15:39:43

0

虽然sed是完全合适的,它不允许超过9个反向引用。 Perl的作用:

echo "a b c d e f g h i j k l m n o p q r s t u v w x y z" | \ 
    perl -lpe 's/(\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+)/$1;$2;$3;$4;$5;$6;$7;$8;$9;$10;$11;$12;$13;$14;$15;$16;$17;$18;$19;$20;$21;$22;$23;$24;$25;$26/g' 
a;b;c;d;e;f;g;h;i;j;k;l;m;n;o;p;q;r;s;t;u;v;w;x;y;z 

这(哑)如显示有可能走得更远比sed\9