How can I convert a file path to an URI in the command-line?
Example:
/home/MHC/directory with spaces and ümläuts
to
file:///home/MHC/directory%20with%20spaces%20and%20%C3%BCml%C3%A4uts
How can I convert a file path to an URI in the command-line?
Example:
/home/MHC/directory with spaces and ümläuts
to
file:///home/MHC/directory%20with%20spaces%20and%20%C3%BCml%C3%A4uts
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!
encodeduri=$(urlencode -m "$uri")
with $uri
in double quotes!
Dec 26, 2012 at 21:49
%FF
for cyrillic symbols.
Oct 24, 2020 at 8:13
On CentOS, no extra dependencies needed:
$ python -c "import urllib;print urllib.quote(raw_input())" <<< "$my_url"
pathlib
module it could be done via python -c 'import sys,pathlib; print(pathlib.Path(sys.argv[1]).resolve().as_uri())' "$my_url"
pathlib
is only available in Python 3, which is not installed by default on CentOS.
Jun 20, 2019 at 2:06
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
$
echo $path | perl -MURI::file -E 'say URI::file->new(<>)'
with Perl 5.10 (from year 2007) or newer
Apr 2, 2019 at 22:24
Rockallite gave a good answer, but I didn't want to type that every time.
I made a reusable bash function to do this called "file2url". To see where to save bash functions, take a look at this thread on SO.
file2url () {
python -c "import sys, pathlib; print(pathlib.Path(input()).resolve().as_uri())" <<< $1
}
This assumes that you have a python3 installed with the name "python".
You can pass path as argument to the following script:
#!/usr/bin/env gjs
const { Gio } = imports.gi;
let path = Gio.File.new_for_path(ARGV[0]);
let uri = path.get_uri();
print(uri);
To convert from uri to path use the following script:
#!/usr/bin/env gjs
const { Gio } = imports.gi;
let uri = Gio.File.new_for_uri(ARGV[0]);
let path = uri.get_path();
print(path);