如何将“.nmv-fas”的所有实例更改为“title”标签之间的任何内容?
这可以用python还是有更好的方法?
基本上改变:
这个
<html>
<head>
<title>.rtpv05-tl</title>
</head>
<a href="http://www.youversion.com/bible/gen.1.nmv-fas">http://www.youversion.com/bible/gen.1.nmv-fas</a>
<a href="http://www.youversion.com/bible/gen.2.nmv-fas">http://www.youversion.com/bible/gen.2.nmv-fas</a>
<a href="http://www.youversion.com/bible/gen.3.nmv-fas">http://www.youversion.com/bible/gen.3.nmv-fas</a>
<a href="http://www.youversion.com/bible/gen.4.nmv-fas">http://www.youversion.com/bible/gen.4.nmv-fas</a>
<a href="http://www.youversion.com/bible/gen.5.nmv-fas">http://www.youversion.com/bible/gen.5.nmv-fas</a>
对此
<html>
<head>
<title>.rtpv05-tl</title>
</head>
<a href="http://www.youversion.com/bible/gen.1.rtpv05-tl">http://www.youversion.com/bible/gen.1.rtpv05-tl</a>
<a href="http://www.youversion.com/bible/gen.2.rtpv05-tl">http://www.youversion.com/bible/gen.2.rtpv05-tl</a>
<a href="http://www.youversion.com/bible/gen.3.rtpv05-tl">http://www.youversion.com/bible/gen.3.rtpv05-tl</a>
<a href="http://www.youversion.com/bible/gen.4.rtpv05-tl">http://www.youversion.com/bible/gen.4.rtpv05-tl</a>
<a href="http://www.youversion.com/bible/gen.5.rtpv05-tl">http://www.youversion.com/bible/gen.5.rtpv05-tl</a>
最佳答案
awk -v text='.nmv-fas' '
/<title>/ {title=$0; gsub(/<\/?title>/, "", title); replace=1}
replace {gsub(text, title)}
{print}
' file > file.tmp && mv file.tmp file
awk 没有像 sed 的
-i
这样的“就地”选项。当然,这取决于标题文本是否与
<title>
位于同一行。标签。为了安全起见,您应该使用 HTML 解析器来解析 HTML。
关于python替换为捕获组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10540379/