使用shell脚本复制HTML文件中的title标记

pepwfjgg  于 2022-11-16  发布在  Shell
关注(0)|答案(2)|浏览(124)

我有两个HTML文件-a.htmlb.html。我想用a.html中的title标签替换b.html中的title标签。
我知道如何使用sed命令在同一个文件中进行简单的替换。

一个.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document AAAAA</title>
</head>
<body>
    This is Document A
</body>
</html>

B.html格式

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document BBBB</title>
</head>
<body>
    This is Document B
</body>
</html>

B.html -运行脚本后-注意“文档BBBBB”已更改为“文档AAAAA”

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document AAAAA</title>
</head>
<body>
    This is Document B
</body>
</html>
aiqt4smr

aiqt4smr1#

GNU的sed

title=`sed -n "s/^.*<title>\(.*\)<\/title>.*$/\1/p" a.html`; \
sed -i "s/^\(.*<title>\).*\(<\/title>.*\)$/\1$title\2/" b.html

BSD/操作系统X sed

title=`sed -n "s/^.*<title>\(.*\)<\/title>.*$/\1/p" a.html`; \
sed -i '' "s/^\(.*<title>\).*\(<\/title>.*\)$/\1$title\2/" b.html

实际上,它使用a.html,用其标题(\1组)替换内容,并将结果设置为title变量。
然后使用一个非常类似的正则表达式,它将b.html中的标题替换为变量,并保存b.html

vsnjm48y

vsnjm48y2#

sed -i 's@BBBBB@AAAAA@' b.html

这样行吗?

相关问题