Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How can I convert a file path to an URI in the command-line?


/home/MHC/directory with spaces and ümläuts


share|improve this question
up vote 4 down vote accepted

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


echo -n file://; urlencode -m "$1"

Many thanks to Michael Kjörling for the references!

share|improve this answer
Don't forget the quotes! You probably want encodeduri=$(urlencode -m "$uri") with $uri in double quotes! – gniourf_gniourf Dec 26 '12 at 21:49
@gniourf_gniourf Thank you, modified the code accordingly. – Glutanimate Dec 26 '12 at 21:55

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"'
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.