AWK内的URL解码

Mik*_*ikA 4 awk urldecode

我文件中的一列是url编码的,我必须解码该列,并需要根据列内的值执行一些操作.有什么办法可以解码awk中的那列吗?

Syl*_*oux 5

你必须根据你的文件格式进行调整,但基本原则在这里(用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 !
Run Code Online (Sandbox Code Playgroud)

如果你有gawk,你可以将它包装在一个函数中(在下面的评论中归功于brendanh):

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;
}
Run Code Online (Sandbox Code Playgroud)