【问题标题】:URL decoding inside AWK [duplicate]AWK中的URL解码[重复]
【发布时间】:2013-06-08 19:02:38
【问题描述】:

我文件中的一列是 url 编码的,我必须对该列进行解码,并且需要根据列内的值执行一些操作。有什么方法可以在 awk 中解码该列?

【问题讨论】:

  • 这个问题不是上面提到的问题的重复,它的标题是错误的。
  • 这不是重复的。这个问题的答案为我解决了另一个问题没有解决的问题。

标签: awk urldecode


【解决方案1】:

你必须根据你的文件格式来调整它,但基本原则在这里(用 GNU Awk 3.1.7 测试):

sh$ echo 'Hello%2C%20world%20%21' | awk '
     {
         for (i = 0x20; i < 0x40; ++i) {
             repl = sprintf("%c", i);
             if ((repl == "&") || (repl == "\\"))
                 repl = "\\" repl;
             gsub(sprintf("%%%02X", i), repl);
             gsub(sprintf("%%%02x", i), repl);
         }
         print
     }
 '
Hello, world !

如果你有gawk,你可以把它包装在一个函数中(感谢brendanh in a comment below):

function urlDecode(url) {
    for (i = 0x20; i < 0x40; ++i) {
        repl = sprintf("%c", i);
        if ((repl == "&") || (repl == "\\")) {
            repl = "\\" repl;
        }
        url = gensub(sprintf("%%%02X", i), repl, "g", url);
        url = gensub(sprintf("%%%02x", i), repl, "g", url);
    }
    return url;
}

【讨论】:

  • 我的字符串是这样的:'http%3a%2f%2fwww.gazelle.com%2fiphone%2fiphone-3g' 上面的操作无法解码这个字符串..:(
  • 显然,我使用了 '%02X' 格式,它匹配用 大写 中的百分号编码的 URL,例如 http%3A%2F... 我修改了示例代码以转换小写百分比-编码也是。现在它应该适用于两者......至少高达%40(for循环的上限)。您可能需要调整它...
  • 我的字符串是这样的:1370474740&http%3a%2f%2fwww.xxxx.com%2fiphone%2fiphone-3g&et%3da%26ago%3d212%26ao%3d219%26px%3d73%26av1%3d2% 26av2%3dOrganicSearch&13456 当我像这样使用 awk 时: awk 'BEGIN {FS = "&"} {for (i = 0x20; i
  • 这个太难了!我不记得&amp;\ gsub 的替换字符串中具有特殊含义。它在答案中是固定的(我希望)
  • 虽然这个功能有效,但速度很慢,我在这里找到了一个快得多的功能github.com/Knorkebrot/werc/blob/master/bin/contrib/…
猜你喜欢
  • 2011-09-25
  • 2012-11-29
  • 1970-01-01
  • 2014-02-20
  • 1970-01-01
  • 1970-01-01
  • 2016-12-11
  • 1970-01-01
  • 2012-03-28
相关资源
最近更新 更多