2010-12-20 42 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