【问题标题】:Using Sed after grep to replace inline with an HTML prefix在 grep 之后使用 Sed 将内联替换为 HTML 前缀
【发布时间】:2023-03-03 11:10:02
【问题描述】:

我想用实际链接替换一些文本。

文字如下:

Some text here 
[...]
-   CRAN Task View: [Bayesian](Bayesian.html)
-   CRAN Task View: [Cluster](Cluster.html)
-   CRAN Task View: [Databases](Databases.html)
-   CRAN Task View: [Environmetrics](Environmetrics.html)
[...]
End of text here

但正如您所见,这些页面没有 HTML 链接。例如,Bayesian.html 应该是http://cran.rstudio.com/web/views/Bayesian.html

最终结果应该是

Some text here 
[...]
-   CRAN Task View: [Bayesian](http://cran.rstudio.com/web/views/Bayesian.html)
-   CRAN Task View: [Cluster](http://cran.rstudio.com/web/views/Cluster.html)
-   CRAN Task View: [Databases](http://cran.rstudio.com/web/views/Databases.html)
-   CRAN Task View: [Environmetrics](http://cran.rstudio.com/web/views/Environmetrics.html)
[...]
End of text here

到目前为止,我可以使用以下命令对我的文本文件进行“子集化”:

grep "CRAN Task View: \[" $FILE

但是当我尝试通过管道传输时:

sed -e 's|\\([a-zA-Z]*\\)\\.html|http://cran.rstudio.com/web/views/\\1.html|'

它不起作用。如何从 grep 命令内联 sed?

我使用的是 macOS Mojave。

【问题讨论】:

    标签: html bash macos sed grep


    【解决方案1】:

    这个sed 应该适合你:

    sed -E '/CRAN Task View:/s~\(([^)]+)\)~(http://cran.rstudio.com/web/views/\1)~' file
    
    Some text here
    [...]
    -   CRAN Task View: [Bayesian](http://cran.rstudio.com/web/views/Bayesian.html)
    -   CRAN Task View: [Cluster](http://cran.rstudio.com/web/views/Cluster.html)
    -   CRAN Task View: [Databases](http://cran.rstudio.com/web/views/Databases.html)
    -   CRAN Task View: [Environmetrics](http://cran.rstudio.com/web/views/Environmetrics.html)
    [...]
    End of text here
    

    正则表达式详细信息:

    • /CRAN Task View:/:仅当行匹配文本"CRAN Task View:"
    • s~:替补
    • \(:匹配一个(
    • ([^)]+):匹配捕获组 #1 中的 1+ 个非) 字符
    • \):匹配一个)
    • (http://cran.rstudio.com/web/views/\1) 是使用反向引用#1 创建链接的替换

    【讨论】:

      【解决方案2】:

      sed -e 's|\\([a-zA-Z]*\\)\\.html|http://cran.rstudio.com/web/views/\\1.html|' 它不起作用。

      这是一个引用问题。内单引号 '...' 反斜杠 \ 不需要转义。 Bash 将'\\(' 解析为\\( 并将其发送到sed,后者将其解释为文字字符串\(。因此,您将替换文件中从未出现过的文字字符串 " \(someLetters\)\.html "

      你的意思可能是sed 's|\([a-zA-Z]*\)\.html|http://cran.rstudio.com/web/views/\1.html|'

      顺便说一句:sed 也可以为你做grep 部分。此外,使用 -E 您需要更少的反斜杠。但是由于您再次附加 .html,因此您首先不需要组 \(....\)

      sed -E -n '/CRAN Task View: \[/s|[a-zA-Z]*\.html|http://cran.rstudio.com/web/views/&|p'
      

      【讨论】:

        猜你喜欢
        • 2016-06-17
        • 2013-11-08
        • 2011-11-03
        • 2021-10-30
        • 2017-09-19
        • 1970-01-01
        • 2014-01-13
        • 2018-02-24
        • 2010-11-29
        相关资源
        最近更新 更多