【问题标题】:regex to add filename into html document正则表达式将文件名添加到 html 文档中
【发布时间】:2023-03-09 12:35:01
【问题描述】:

我正在寻找一种编辑数千个 .html 文件的方法,将它们添加为 og:url ,其 URL 基本上取自文件名。基本上,对于我想要的每个 .html:

<meta property="og:url" content="https://www.example.com/NAME-OF-THE-FILE.html" />

--

我的想法是搜索 并将其替换为所需的代码: 我不知道如何找到文件名。如何做到这一点?

--

简单来说:

我在所有 .html 文件中搜索和替换。

地点:

</head>

替换为:

<meta property="og:url" content="https://www.example.com/{FILENAME}" />
</head>

我该怎么做?我不知道如何获取 {FILENAME}(文件名)

编辑:Bash 看起来很有趣,但我是个菜鸟,不知道如何获得它。非常欢迎任何帮助。

谢谢,谢谢,谢谢!

【问题讨论】:

    标签: html regex bash notepad++


    【解决方案1】:

    如果你可以在 bash 中访问,你可以运行这个小脚本:

    for i in *.html;do
      sed -i "s/</head>/<metaproperty=\"og:url\"content=\"https://www.example.com/$i\"/</head>/g" "$i"
    done
    

    编辑:遗漏了一些反斜杠。正确的 sed 命令是:

    sed -i "s/<\/head>/<meta property=\"og:url\" content=\"https:\/\/www.example.com\/$i\" \/><\/head>/g" "$i"
    

    【讨论】:

    • 谢谢@Alator,但我收到一个错误:sed: -e expression #1, char 11: unknown option to `s'
    • 抱歉打错了。sed 命令必须是这样的:sed -i "s///g" "$i"
    • 那里,抱歉我一开始没找到。接受!
    【解决方案2】:

    您能否尝试在单个 .html 文件上执行以下命令,如果这对您有帮助,请告诉我,如果您发现它适用于单个文件,您可以将其用于所有 html 文件。这是在 powershell 中,它主要是内置在 windows 中的。(请先在 1 个文件上尝试它们,因为我没有测试它们)

    (Get-Content test.html) | ForEach-Object { $_ -replace "</head>", "<meta property="og:url" content="https://www.example.com/{FILENAME}" />\n</head>" } | Out-File test.html
    

    powershell -Command "(gc test.html) -replace '</head>', '<meta property="og:url" content="https://www.example.com/{FILENAME}" />\n></head>' | Out-File test.html"
    

    【讨论】:

    • 这让我很接近,但它显示 {FILENAME} 而不是文件名。我希望它在那里打印文件的名称。 (第一个代码的答案,第二个没有运行)谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-20
    • 2021-07-24
    • 2018-08-02
    • 2012-01-13
    • 1970-01-01
    • 2013-05-30
    相关资源
    最近更新 更多