如何在shell中解码URL编码的字符串? [英] How to decode URL-encoded string in shell?

查看:86
本文介绍了如何在shell中解码URL编码的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件,其中包含已编码的用户代理列表.例如:

I have a file with a list of user-agents which are encoded. E.g.:

Mozilla%2F5.0%20%28Macintosh%3B%20U%3B%20Intel%20Mac%20OS%20X%2010.6%3B%20en

我想要一个 shell 脚本,它可以读取这个文件并用解码的字符串写入一个新文件.

I want a shell script which can read this file and write to a new file with decoded strings.

Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en

我一直在尝试使用这个示例来实现它,但到目前为止还没有奏效.

I have been trying to use this example to get it going but it is not working so far.

$ echo -e "$(echo "%31+%32%0A%33+%34" | sed 'y/+/ /; s/%/\x/g')"

我的脚本看起来像:

#!/bin/bash
for f in *.log; do
  echo -e "$(cat $f | sed 'y/+/ /; s/%/x/g')" > y.log
done

推荐答案

这是一个简单的单行解决方案.

Here is a simple one-line solution.

$ function urldecode() { : "${*//+/ }"; echo -e "${_//%/\x}"; }

它可能看起来像 perl :) 但它只是纯粹的 bash.没有 awks,没有 seds ......没有开销.使用 : 内置、特殊参数、模式替换和 echo 内置的 -e 选项将十六进制代码转换为字符.有关更多详细信息,请参阅 bash 的联机帮助页.您可以将此功能用作单独的命令

It may look like perl :) but it is just pure bash. No awks, no seds ... no overheads. Using the : builtin, special parameters, pattern substitution and the echo builtin's -e option to translate hex codes into characters. See bash's manpage for further details. You can use this function as separate command

$ urldecode https%3A%2F%2Fgoogle.com%2Fsearch%3Fq%3Durldecode%2Bbash
https://google.com/search?q=urldecode+bash

或者在变量赋值中,像这样:

or in variable assignments, like so:

$ x="http%3A%2F%2Fstackoverflow.com%2Fsearch%3Fq%3Durldecode%2Bbash"
$ y=$(urldecode "$x")
$ echo "$y"
http://stackoverflow.com/search?q=urldecode+bash

这篇关于如何在shell中解码URL编码的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆