Linux sed 从 html 文件中删除标签

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19878056/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 01:18:01  来源:igfitidea点击:

Sed remove tags from html file

htmlregexlinuxbash

提问by michste93

I need to remove all tags from a html with a bash script using the sed command. I tried with this

我需要使用 sed 命令从带有 bash 脚本的 html 中删除所有标签。我试过这个

sed -r 's/[\<][\/]?[a-zA-Z0-9\=\"\-\#\.\& ]+[\/]?[\>]//g' 

and whith this

和这个

sed -r 's/[\<][\/]?[.]*[\/]?[\]?[\>]//g' 

but I still miss something, any suggestions??

但我还是想念一些东西,有什么建议吗??

采纳答案by Olaf Dietsche

You can either use one of the many HTML to text converters, use Perl regex if possible <.+?>or if it must be seduse <[^>]*>

您可以使用很多的一个HTML文本转换器,使用Perl的正则表达式如果可能的话<.+?>,或者如果它必须是sed使用<[^>]*>

sed -e 's/<[^>]*>//g' file.html

If there's no room for errors, use an HTML parser instead. E.g. when an element is spread over two lines

如果没有错误的余地,请改用 HTML 解析器。例如,当一个元素分布在两行上时

<div
>Lorem ipsum</div>

this regular expression will not work.

这个正则表达式不起作用。



This regular expression consists of three parts <, [^>]*, >

这正则表达式由三个部分组成<[^>]*>

  • search for opening <
  • followed by zero or more characters *, which are not the closing >
    [...]is a character class, when it starts with ^look for characters notin the class
  • and finally look for closing >
  • 寻找开放 <
  • 后跟零个或多个字符*(不是结束字符)>
    [...]字符类,当它以^查找不在类中的字符开始时
  • 最后寻找关闭 >

The simpler regular expression <.*>will not work, because it searches for the longest possible match, i.e. the last closing >in an input line. E.g., when you have more than one tag in an input line

更简单的正则表达式<.*>将不起作用,因为它搜索可能的最长匹配项,即>输入行中的最后一个结尾。例如,当您在输入行中有多个标签时

<name>Olaf</name> answers questions.

will result in

会导致

answers questions.

回答问题。

instead of

代替

Olaf answers questions.

奥拉夫回答问题。

See also Repetition with Star and Plus, especially section Watch Out for The Greediness!and following, for a detailed explanation.

另见用 Star 和 Plus 重复,特别是注意贪婪部分!以及下面的详细解释。