【问题标题】:Find and replace URL with content from URL使用 URL 中的内容查找和替换 URL
【发布时间】:2017-06-19 11:06:38
【问题描述】:

背景信息: 我有一个 XML 文件,我的供应商每晚都会上传新产品和更新的库存数量等。 但是他们把我缝合了,他们在 XML 文件中没有描述,他们有一个指向他们网站的链接,其中包含原始文本的描述。

我需要做的是有一个脚本循环遍历我从他们那里下载的文档,并将 URL 替换为 URL 的内容。

例如,如果我有

<DescriptionLink>http://www.leadersystems.com.au/DataFeed/ProductDetails/AT-CHARGERSTATION-45</DescriptionLink>

我希望它最终成为

<DescriptionLink>Astrotek USB Charging Station Charger Hub 3 Port 5V 4A with 1.5m Power Cable White for iPhone Samsung iPad Tablet GPS</DescriptionLink>

我已经尝试了一些东西,但我对脚本或循环不是很精通。 到目前为止,我得到了:

#!/bin/bash
LINKGET=`awk -F '|' '{ print $2 }' products-daily.txt`

wget -O products-daily.txt http://www.suppliers-site-url.com
sed 's/<DescriptionLink>*/<DescriptionLink>$(wget -S -O- $LINKGET/g' products-daily.txt

但同样,我不确定这一切是如何真正起作用的,所以它一直在反复试验。 任何帮助表示赞赏!!!

更新为包含示例 URL。

【问题讨论】:

  • 您能提供一个网址示例吗?否则很难测试...
  • 添加 URL 例如:)

标签: bash loops url awk sed


【解决方案1】:

你会想要这样的东西(使用 GNU awk 作为第三个参数来匹配()):

$ cat tst.awk
{
    head = ""
    tail = encode($0)
    while ( match(tail,/^([^{]*[{])([^}]+)(.*)/,a) ) {
        desc = ""
        cmd = "curl -s \047" a[2] "\047"
        while ( (cmd | getline line) > 0 ) {
            desc = (desc=="" ? "" : desc ORS) line
        }
        close(cmd)
        head = head decode(a[1]) desc
        tail = a[3]
    }
    print head decode(tail)
}
function encode(str) {
    gsub(/@/,"@A",str)
    gsub(/{/,"@B",str)
    gsub(/}/,"@C",str)
    gsub(/<DescriptionLink>/,"{",str)
    gsub(/<\/DescriptionLink>/,"}",str)
    return str
}
function decode(str) {
    gsub(/}/,"</DescriptionLink>",str)
    gsub(/{/,"<DescriptionLink>",str)
    gsub(/@C/,"}",str)
    gsub(/@B/,"{",str)
    gsub(/@A/,"@",str)
    return str
}

$ awk -f tst.awk file
<DescriptionLink>Astrotek USB Charging Station Charger Hub 3 Port 5V 4A with 1.5m Power Cable White for iPhone Samsung iPad Tablet GPS</DescriptionLink>

请参阅https://stackoverflow.com/a/40512703/1745001,了解有关编码/解码功能的作用及其原因的信息。

请注意,这是适合使用getline 的少数情况之一。如果您将来考虑使用getline,请确保您首先阅读并完全理解http://awk.freeshell.org/AllAboutGetline 讨论的所有注意事项和用例。

【讨论】:

  • 对文件中的 5000 多个条目运行此命令时,我收到一条错误消息,提示 fatal: cannot open pipe `curl -s (Too many open files)Any idea's Ed?
  • 是的,我忘记在每次通话后关闭管道,就像我在答案底部引用的那篇文章中显示的那样(请参阅其中的a) Reading from a pipe)。现已修复。
猜你喜欢
  • 2021-11-19
  • 1970-01-01
  • 2011-09-15
  • 2017-03-26
  • 2014-06-13
  • 1970-01-01
  • 1970-01-01
  • 2015-07-20
  • 2012-05-05
相关资源
最近更新 更多