Convert file path to URI in bash
One way to do this is using urlencode
(install it on Ubuntu via sudo apt-get install gridsite-clients
).
urlencode -m "$filepath"
will convert the path to an URI. The "file://" part of the URI will be left out, but you can easily add that via a bash one-liner:
uri=$(urlencode -m "$1"); echo "file://$uri"
or directly
echo "file://$(urlencode -m "$1")"
or
echo -n file://; urlencode -m "$1"
Many thanks to Michael Kjörling for the references!
On CentOS, no extra dependencies needed:
$ python -c "import urllib;print urllib.quote(raw_input())" <<< "$my_url"
You can also use the Perl module URI::file directly from the command line:
$ path="/home/MHC/directory with spaces and ümläuts"
$ echo $path | perl -MURI::file -e 'print URI::file->new(<STDIN>)."\n"'
file:///home/MHC/directory%20with%20spaces%20and%20%C3%BCml%C3%A4uts
$