4

我目前正在验证客户的 HTML 源代码,并且我收到很多没有 Omittag 的图像和输入文件的验证错误。我会手动完成,但这个客户端实际上有数千个文件,其中很多实例不是 .

这个客户已经验证了一些 img 标签(无论出于何种原因)。

只是想知道是否有一个 unix 命令我可以运行来检查是否没有 Omittag 来添加它。

我已经完成了简单的搜索并用以下命令替换:

find . \! -path '*.svn*' -type f -exec sed -i -n '1h;1!H;${;g;s/<b>/<strong>/g;p}' {} \; 

但从来没有这么大的东西。任何帮助,将不胜感激。

4

2 回答 2

4

试试这个。它将遍历您的文件,.orig对每个文件(perl 的运算符)进行备份,并用and-i替换<img>and<input>标记。<img /><input >

find . \! -path '*.svn*' -type f -exec perl -pi.orig -e 's{ ( <(?:img|input)\b ([^>]*?) ) \ ?/?> }{$1\ />}sgxi' {} \;

给定输入:

<img>  <img/>  <img src="..">  <img src="" >
<input>  <input/>  <input id="..">  <input id="" >

它将文件更改为:

<img />  <img />  <img src=".." />  <img src="" />
<input />  <input />  <input id=".." />  <input id="" />

这是正则表达式正在做的事情:

s{(<(?:img|input)\b ([^>]*?)) # capture "<img" or "<input" followed by non-">" chars
  \ ?/?>}                     # optional space, optional slash, followed by ">"
{$1\ />}sgxi                  # replace with: captured text, plus " />"
于 2008-10-28T06:15:29.520 回答
0

请参阅我在顶部评论中提出的问题。

假设您使用的是 GNU sed,并且您正在尝试尾随添加/到您的标签以使 XML 兼容<img />and <input />,然后用这个替换命令中的 sed 表达式,它应该可以解决问题:'1h;1!H;${;g;s/\(img\|input\)\( [^>]*[^/]\)>/\1\2\/>/g;p;}'

这是一个简单的测试文件(SO的着色器做古怪的事情):

$ cat test.html
This is an <img tag> without closing slash.
Here is an <img tag /> with closing slash.
This is an <input tag > without closing slash.
And here one <input attrib="1" 
    > that spans multiple lines.
Finally one <input
  attrib="1" /> with closing slash.

$ sed -n '1h;1!H;${;g;s/\(img\|input\)\( [^>]*[^/]\)>/\1\2\/>/g;p;}' test.html
This is an <img tag/> without closing slash.
Here is an <img tag /> with closing slash.
This is an <input tag /> without closing slash.
And here one <input attrib="1" 
    /> that spans multiple lines.
Finally one <input
  attrib="1" /> with closing slash.

这是GNU sed 正则表达式语法以及缓冲如何进行多行搜索/替换

或者,您可以使用类似Tidy之类的东西,它是为清理不良 HTML 而设计的——如果我做的事情比几个简单的搜索/替换更复杂,我就会这样做。Tidy 的选项很快就会变得复杂,因此通常最好用您选择的脚本语言(Python、Perl)编写一个脚本来调用libtidy和设置您需要的任何选项。

于 2008-10-28T06:16:18.847 回答