출처:
http://geni.ath.cx/unix.html
One-liner urldecode functions
awk
#!/bin/sh
# (C) 2006 GPL by Huidae Cho
awk '
BEGIN{
for(i = 0; i < 10; i++)
hex[i] = i
hex["A"] = hex["a"] = 10
hex["B"] = hex["b"] = 11
hex["C"] = hex["c"] = 12
hex["D"] = hex["d"] = 13
hex["E"] = hex["e"] = 14
hex["F"] = hex["f"] = 15
}
{
gsub(/\+/, " ")
i = $0
while(match(i, /%../)){
if(RSTART > 1)
printf "%s", substr(i, 1, RSTART-1)
printf "%c", hex[substr(i, RSTART+1, 1)] * 16 + hex[substr(i, RSTART+2, 1)]
i = substr(i, RSTART+RLENGTH)
}
print i
}
'
OK, OK, I said "One-liner" urldecode functions. Try this! :-)
$ alias urldecode="awk '"'BEGIN{for(i=0;i<10;i++)hex[i]=i;hex["A"]=hex["a"]=10;hex["B"]=hex["b"]=11;hex["C"]=hex["c"]=12;hex["D"]=hex["d"]=13;hex["E"]=hex["e"]=14;hex["F"]=hex["f"]=15;}{gsub(/\+/," ");i=$0;while(match(i,/%../)){;if(RSTART>1);printf"%s",substr(i,1,RSTART-1);printf"%c",hex[substr(i,RSTART+1,1)]*16+hex[substr(i,RSTART+2,1)];i=substr(i,RSTART+RLENGTH);}print i;}'"'"
$ echo "%31+%32%0A%33+%34" | urldecode
1 2
3 4
GNU sed
This script uses an extension of GNU sed (\xNN).
# (C) 2006 GPL by Huidae Cho
urldecode(){
echo "$@" | sed 's/^.*$/'"`echo "$@" | sed 'y/+/ /; s/%/\\\\x/g; s/\//\\\\\//g'`"'/'
}
$ urldecode "%31+%32%0A%33+%34"
1 2
3 4
GNU Bourne-Again Shell (bash) and sed
It's extremely fast!
# (C) 2004 GPL by Huidae Cho
urldecode(){
echo -e "$(sed 'y/+/ /; s/%/\\x/g')"
}
$ echo "%31+%32%0A%33+%34" | urldecode
or
$ echo -e "$(echo "%31+%32%0A%33+%34" | sed 'y/+/ /; s/%/\\x/g')"
outputs
1 2
3 4
Pure bash version: http://thijs.dalhuijsen.com/code/index.shtml?req=5