K
K
KawaiDesu2013-12-04 17:05:08
bash
KawaiDesu, 2013-12-04 17:05:08

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

2 answer(s)
B
bmkobzar, 2013-12-04
@KawaiDesu

#!/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" )

You can come up with the processing of Russian letters yourself,
here is the php implementation

O
Opaspap, 2013-12-04
@Opaspap

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";

the first argument is a string, the second argument, if it exists, then decode the string, if not, encode it.
the URI::Encode module is written in perl, small, it can be installed from your distro repository using cpan or copy-pasted from source. perl is on almost every system.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question