harttle.github.io icon indicating copy to clipboard operation
harttle.github.io copied to clipboard

2019/03/01/encode-uri-component-with-bash

Open utterances-bot opened this issue 6 years ago • 3 comments

在 Bash 中进行 encodeURIComponent/decodeURIComponent | Harttle Land

URL Encoding 又叫百分号编码,定义在 URL 标准 中。在前端通过 encodeURI 和 encodeURIComponent 来分别编码 URL 和 URL 参数。那么在 Bash 中怎么编解码呢?这在写处理网页或链接的脚本时非常有用...

https://harttle.land/2019/03/01/encode-uri-component-with-bash.html

utterances-bot avatar Mar 08 '19 03:03 utterances-bot

解码(二)

对百分号解码我之前实现了另外一种方法

echo -n %e8%a7%a3%e7%a0%81 | tr -d % | xxd -r -p

xxd-r 是让 hexdump 格式转为正常的二进制格式, -p 是告诉 xxd 要转换的内容没有多余的 ascii 内容

针对有些百分号编码的是 GBK 或者 GB2312 等字符集,可以在后面加上 iconv -f gb2312 -t utf8

echo -n %bd%e2%c2%eb | tr -d % | xxd -r -p | iconv -f gb2312 -t utf8

你的不少文章感觉都有所收益,碰巧之前我也弄过这一块,就发过来了。

yantze avatar Mar 08 '19 03:03 yantze

我在写这篇文章之前也是用的这种办法(毕竟就是编码命令的反函数),但它有一个缺陷:浏览器 encodeURIComponent API 不会编码不需要编码的字符。比如 echo -n http%3a%2f%2fharttle.land | tr -d % | xxd -r -p 就只会返回 ://

harttle avatar Mar 08 '19 04:03 harttle

想了一下,直接用 node 命令行要容易记一些:

node -e "console.log(decodeURIComponent('http%3a%2f%2fharttle.land'))"

之前要用 gbk 转 utf8 在 node 上太麻烦了,所以就想到了我之前发的那个想法。

使用管道传输:

echo 'http%3a%2f%2fharttle.land' | node -e "process.stdin.on('data', data => process.stdout.write(decodeURIComponent(data.toString())))"

yantze avatar Mar 14 '19 00:03 yantze