2011-07-04 74 views
0

我想使用這種模式的4chan的線程獲取主板名稱:sed -n s/pattern/ 1/p打印既匹配又不匹配?

echo $(cat ~/Desktop/test.html | sed -n "s/<title>\(.*\) - />\1</p") 

的test.html包含:

<link rel="shortcut icon" href="http://static.4chan.org/image/favicon.ico" /><link rel="stylesheet" type="text/css" href="http://static.4chan.org/css/yotsuba.9.css" title="Yotsuba"><link rel="alternate stylesheet" type="text/css" href="http://static.4chan.org/css/yotsublue.9.css" title="Yotsuba B"><link rel="alternate stylesheet" type="text/css" href="http://static.4chan.org/css/futaba.9.css" title="Futaba"><link rel="alternate stylesheet" type="text/css" href="http://static.4chan.org/css/burichan.9.css" title="Burichan"><title>/b/ - Random</title> 

我想匹配/ B /,而是它只是刪除「 <title> 「和」 -「像這樣:

<link rel="shortcut icon" href="http://static.4chan.org/image/favicon.ico" /><link rel="stylesheet" type="text/css" href="http://static.4chan.org/css/yotsuba.9.css" title="Yotsuba"><link rel="alternate stylesheet" type="text/css" href="http://static.4chan.org/css/yotsublue.9.css" title="Yotsuba B"><link rel="alternate stylesheet" type="text/css" href="http://static.4chan.org/css/futaba.9.css" title="Futaba"><link rel="alternate stylesheet" type="text/css" href="http://static.4chan.org/css/burichan.9.css" title="Burichan">>/b/<Random</title> 

爲什麼?

回答

1

因爲這就是你所說的全部替代。如果你想從頭到尾移除,那麼你需要用^$來定位兩端,並匹配所有的字符。

1

事情是這樣的:

sed -n "s/.*<title>\([^<>]*\) - .*/\1/p" ~/Desktop/test.html 

您的問題是你的正則表達式不匹配字符串的開頭(在我的情況下,*做到這一點」和字符串的結尾(又在我的情況下,它「。*」最後)