【问题标题】:Script to extract strings between two strings in linux在linux中提取两个字符串之间的字符串的脚本
【发布时间】:2019-03-03 16:07:41
【问题描述】:

我正在尝试编写一个小脚本,让我可以从我的 rss 阅读器(newsboat)中“捕获”文章。所以我的场景是这样的:我将文章通过管道传输到脚本;然而,这篇文章被排成一行,如下所示:

Title: ABC boss quits over Australian political interference claims Author: Date: Thu, 27 Sep 2018 09:39:16 +0200 Link: https://www.bbc.co.uk/news/world-australia-45661871 The broadcaster's chair quits amid allegations the government leaned on him to dismiss two journalists.

所以我需要做的是将链接和标题一致地存储在一个变量中,然后使用这些变量调用一个命令(emacsclient org-protocol:/ ...)

所以基本上我需要这个:

TITLE="ABC boss quits over Australian political interference claims"
URL="https://www.bbc.co.uk/news/world-australia-45661871"

我考虑过使用 awk 或 sed,但它们最适合单独的行。所以,我想也许可以在“标题:”、“作者:”、“日期:”和“链接:”处拆分单行,然后用 awk/sed 提取。

我在这里发现了类似的用例和问题,但并不完全相同。我想要一个非常小的脚本,而不必使用 python。

我走对了吗?

感谢您的帮助。

【问题讨论】:

    标签: string awk sed


    【解决方案1】:

    使用 GNU awk 将第三个参数匹配():

    $ cat tst.awk
    match($0,/^Title:\s*(.*)\s+Author:\s*(.*)\s+Date:\s*(.*)\s+Link:\s*(\S+)\s+(.*)/,a) {
        printf "TITLE=\"%s\"\n", a[1]
        printf "URL=\"%s\"\n", a[4]
    }
    
    $ awk -f tst.awk file
    TITLE="ABC boss quits over Australian political interference claims"
    URL="https://www.bbc.co.uk/news/world-australia-45661871"
    

    我还展示了如何保存所有其他字段,以便您还可以对输入进行任何其他操作。

    【讨论】:

      【解决方案2】:

      这可能对你有用(GNU sed):

      sed -r 's/^Title: (.*) Author:.* Link: (\S+).*/TITLE="\1"\nURL="\2"/' file
      

      使用模式匹配来提取所需的字段。第一个可能包含空格,因此匹配键 Author:。第二个是键Link:之后的一串非空格字符。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-07-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-31
        • 2013-12-11
        • 1970-01-01
        相关资源
        最近更新 更多