简体   繁体   English

如何仅打印sed匹配项?

[英]How to print only matches with sed?

Okay, this is an easy one, but I can't figure it out. 好的,这很简单,但是我无法弄清楚。

Basically I want to extract all links ( <a href="[^<>]*">[^<>]*</a> ) from a big html file. 基本上,我想从一个大的html文件中提取所有链接( <a href="[^<>]*">[^<>]*</a> )。

I tried to do this with sed , but I get all kinds of results, just not what I want. 我试图用sed来做到这一点,但是我得到了各种各样的结果,但不是我想要的。 I know that my regexp is correct, because I can replace all the links in a file: 我知道我的regexp是正确的,因为我可以替换文件中的所有链接:

sed 's_<a href="[^<>]*">[^<>]*</a>_TEST_g'

If I run that on something like 如果我在类似的东西上运行

<div><a href="http://wwww.google.com">A google link</a></div>
<div><a href="http://wwww.google.com">A google link</a></div>

I get 我懂了

<div>TEST</div>
<div>TEST</div>

How can I get rid of everything else and just print the matches instead? 我该如何摆脱其他一切,而只打印比赛? My preferred end result would be: 我首选的最终结果是:

<a href="http://wwww.google.com">A google link</a>
<a href="http://wwww.google.com">A google link</a>

PS. PS。 I know that my regexp is not the most flexible one, but it's enough for my intentions. 我知道我的regexp不是最灵活的,但足以满足我的意图。

Match the whole line, put the interesting part in a group, replace by the content of the group. 匹配整行,将有趣的部分放在组中,然后替换为组的内容。 Use the -n option to suppress non-matching lines, and add the p modifier to print the result of the s command. 使用-n选项禁止显示不匹配的行,并添加p修饰符以打印s命令的结果。

sed -n -e 's!^.*\(<[Aa] [^<>]*>.*</[Aa]>\).*$!\1!p'

Note that if there are multiple links on the line, this only prints the last link. 请注意,如果该行上有多个链接,则仅打印最后一个链接。 You can improve on that, but it goes beyond simple sed usage. 您可以对此进行改进,但它不仅限于简单的sed使用。 The simplest method is to use two steps: first insert a newline before any two links, then extract the links. 最简单的方法是使用两个步骤:首先在任何两个链接之前插入换行符,然后解压缩链接。

sed -n -e 's!</a>!&\n!p' | sed -n -e 's!^.*\(<[Aa] [^<>]*>.*</[Aa]>\).*$!\1!p'

This still doesn't handle HTML comments, <pre> , links that are spread over several lines, etc. When parsing HTML, use an HTML parser . 这仍然无法处理HTML注释, <pre> ,分布在多行上的链接等。解析HTML时,请使用HTML解析器

Assuming that there is only one hyperlink per line the following may work... 假设每行只有一个超链接,则可能会起作用...

sed -e 's_.*&lta href=_&lta href=_' -e 's_>.*_>ed <<'EOF'
 -e 's_.*&lta href=_&lta href=_' -e 's_>.*_>_'

If you don't mind using perl like sed it can copy with very diverse input: 如果您不介意使用像sed这样的perl,则可以使用非常多样化的输入进行复制:

perl -n -e 's+(<a href=.*?</a>)+ print $1, "\n" +eg;'

这可能对您有用(GNU sed):

sed '/<a href\>/!d;s//\n&/;s/[^\n]*\n//;:a;$!{/>/!{N;ba}};y/\n/ /;s//&\n/;P;D' file

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM