我將如何刪除錨標記,但將錨文本保留在Bash中?所以我想刪除除了文字示例以外的所有內容。刪除錨標記,但保持錨文本
<a href="http://example.com">Example text</a>
所以,如果我做的:
echo '<a href="http://example.com">Example text</a>' | sed -e 's/<[^>]*>//g'
,去除所有的HTML。我正在尋找刪除只是錨標記,但也保留錨文本...在這種情況下的示例文本。
我將如何刪除錨標記,但將錨文本保留在Bash中?所以我想刪除除了文字示例以外的所有內容。刪除錨標記,但保持錨文本
<a href="http://example.com">Example text</a>
所以,如果我做的:
echo '<a href="http://example.com">Example text</a>' | sed -e 's/<[^>]*>//g'
,去除所有的HTML。我正在尋找刪除只是錨標記,但也保留錨文本...在這種情況下的示例文本。
你可以使用下面的命令:
$ echo '<a href="http://example.com">Example text</a>' | sed -e 's/<[^>]*>//g'
Example text
,或者,你也可以因爲non greedy則表達式中使用perl
代替sed
將是有益的位置:
$ echo '<a href="http://example.com">Example text</a>' | perl -pe 's/\<.*?\>//g'
Example text
注意:使用解析HTML的正則表達式是discouraged,但對於這個小任務,我認爲可以堅持使用命令行中提供的工具。
編輯:只刪除錨點標記,你可以使用正則表達式可以更新如下:
sed -e 's/<\/\?a\s*[^>]*>//g'
這裏是一個有益的指導: http://www.eng.cam.ac.uk/help/tpl/unix/sed.html
如果你的輸入結構良好,你可以從命令行使用XSLT。 (我建議Saxon,但Xalan將是確定。):
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="a">
<xsl:apply-templates/>
</xsl:template>
</xsl:stylesheet>
另見RegEx match open tags except XHTML self-contained tags :-)
我期待用sed只刪除錨點標記並不是所有的標籤。那可能嗎? – user983223 2012-02-07 20:52:14
@ user983223是的,我已經更新了我的答案。 – jcollado 2012-02-07 20:55:24
刪除錨標記不起作用......它仍然顯示我最初回應的所有內容。 – user983223 2012-02-07 22:37:43