python替换为捕获组

标签 python bash ubuntu batch-file

如何将“.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/

相关文章:

c - 如何从 C 程序和 Ubuntu 操作系统读取远程设备的文件?

python - GPU 下的 Tensorflow 比预期慢

php - 从 PHP 脚本执行 shell 脚本

Bash - 添加包含变量的新行

linux - Bash:单引号、双引号和感叹号

gcc - 成功构建了 GCC 交叉编译器工具链。如何正确设置环境变量?

python - BytesIO.truncate 方法不扩展缓冲区内容

python - 如何在 python 中编写多进程 Web 服务器

python - Sublime Text 3-发送命令至Sublime Console

android - ]无法在 Ubuntu 14 中启动 Android Studio