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! %FF for cyrillic symbols. 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. raw_input() was renamed to input() in Python3 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 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".
sys doesn't seem to be used 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);