Answer the question
In order to leave comments, you need to log in
Urlencode in bash?
I am writing a bash script. You need to convert the string to urlencoded, as eg urlencode() in PHP does.
Using other scripting languages (python, php, etc) is not an option. A simple and relatively fast (in terms of execution speed) solution is needed. Also, it is desirable that the utility that performs the operation can be installed on most popular *nix systems, i.e. at least a minimum tolerance is required.
For example, there is an ascii2uni/uni2ascii utility, but it does not encode regular (English) alphabetic characters; I also need the result as with a full-fledged urlencode (for application/x-www-form-urlencoded).
Options?
Answer the question
In order to leave comments, you need to log in
#!/bin/bash
phpurlencode() {
local hexchars="0123456789ABCDEF"
local string="${1}"
local strlen=${#string}
local encoded=""
for (( pos=0 ; pos<strlen ; pos++ )); do
c=${string:$pos:1}
if [ "$c" == ' ' ];then
encoded+='+'
elif ( && [ "$c" \< "0" ] && && ) || ( [ "$c" \< 'A' ] && [ "$c" \> '9' ] ) || ( [ "$c" \> 'Z' ] && [ "$c" \< 'a' ] && ) || ( [ "$c" \> 'z' ] );then
hc=`printf '%X' "'$c"`
dc=`printf '%d' "'$c"`
encoded+='%'
f=$(( $dc >> 4 ))
s=$(( $dc & 15 ))
encoded+=${hexchars:$f:1}
encoded+=${hexchars:$s:1}
else
encoded+=$c
fi
done
echo "${encoded}" # You can either set a return variable (FASTER)
REPLY="${encoded}" #+or echo the result (EASIER)... or both... :p
}
echo $1
echo http://url/q?=$( phpurlencode "$1" )
perl using search.cpan.org/~mithun/URI-Encode-0.09/lib/URI/En...
#!/usr/bin/perl
use URI::Encode qw(uri_encode uri_decode);
my $arg=shift,$decode=shift;
if ($decode) {
print uri_decode($arg);
} else {
utf8::decode($arg);
print uri_encode($arg);
}
print "\n";
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question