【问题标题】:Regex to extract all Starred Items URLs from Google Reader JSON file正则表达式从 Google Reader JSON 文件中提取所有加星标的项目 URL
【发布时间】:2013-04-05 14:35:52
【问题描述】:

遗憾的是,Google Reader 宣布将于今年年中关闭。 由于我在 Google 阅读器中有大量已加星标的项目,我想备份它们。 这可以通过谷歌阅读器外卖来实现。它会生成一个JSON 格式的文件。

现在我想从这个数 MB 的大文件中提取所有文章的 url。

起初我认为最好对 url 使用正则表达式,但似乎最好通过正则表达式提取所需的文章 url 来查找文章 url。这将防止提取其他不需要的 url。

以下是 json 文件部分外观的简短示例:

"published" : 1359723602,
"updated" : 1359723602,
"canonical" : [ {
  "href" : "http://arstechnica.com/apple/2013/02/omni-group-unveils-omnifocus-2-omniplan-omnioutliner-4-for-mac/"
} ],
"alternate" : [ {
  "href" : "http://feeds.arstechnica.com/~r/arstechnica/everything/~3/EphJmT-xTN4/",
  "type" : "text/html"
} ],

我只需要你可以在这里找到的网址:

 "canonical" : [ {
  "href" : "http://arstechnica.com/apple/2013/02/omni-group-unveils-omnifocus-2-omniplan-omnioutliner-4-for-mac/"
} ],

也许有人有心情说正则表达式必须如何提取所有这些 url?

这样做的好处是有一种快速而肮脏的方式从 Google 阅读器中提取加星标的项目网址,以便在处理后将它们导入到 Pocket 或 evernote 等服务中。

【问题讨论】:

  • 不要对正则表达式执行此操作。 正则表达式并不是你在碰巧涉及文本的每一个问题上挥舞的魔杖。使用现有的、编写的、经过测试和调试的 JSON 库。
  • 顺便说一句,我也为谷歌阅读器的关闭感到难过。我发现bloglines.com 是可以接受的替代品。虽然不像阅读器那样响应迅速,但它的界面非常相似,并且可以直接从 Google Takeout XML 输出中导入 OPML。

标签: html regex json url


【解决方案1】:

我知道您询问过正则表达式,但我认为有更好的方法来处理这个问题。多行正则表达式是一个 PITA,在这种情况下,不需要那种脑损伤。

我会从grep 开始,而不是正则表达式。 -A1 参数表示“返回匹配的行,然后返回”:

grep -A1 "canonical" <file>

这将返回如下行:

"canonical" : [ {
    "href" : "http://arstechnica.com/apple/2013/02/omni-group-unveils-omnifocus-2-omniplan-omnioutliner-4-for-mac/"

然后,我会再次 grep 获取 href:

grep -A1 "canonical" <file> | grep "href"

给予

"href" : "http://arstechnica.com/apple/2013/02/omni-group-unveils-omnifocus-2-omniplan-omnioutliner-4-for-mac/"

现在我可以使用 awk 来获取网址:

grep -A1 "canonical" <file> | grep "href" | awk -F'" : "' '{ print $2 }' 

去掉网址上的第一个引号:

http://arstechnica.com/apple/2013/02/omni-group-unveils-omnifocus-2-omniplan-omnioutliner-4-for-mac/"

现在我只需要去掉多余的引号:

grep -A1 "canonical" <file> | grep "href" | awk -F'" : "' '{ print $2 }' | tr -d '"'

就是这样!

http://arstechnica.com/apple/2013/02/omni-group-unveils-omnifocus-2-omniplan-omnioutliner-4-for-mac/

【讨论】:

  • 太棒了,它就像一个魅力。请给我一个提示,我可以如何另外实现为每个项目添加一些字符?我想让它变成这样
  • stern.de/wirtschaft/geld/…>.
  • 也有大约 400 种方法可以做到这一点...... perl 可能是我最喜欢的:... | perl -ne 'chomp; print "&lt;li&gt;&lt;a href=\"$_\"&gt;$_&lt;/a&gt;&lt;/li&gt;\n"'
  • 猜你喜欢
    相关资源
    最近更新 更多
    热门标签