Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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
share|improve this question
add comment

2 Answers

up vote 3 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")"

or

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
add comment

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
$
share|improve this answer
add comment

Your Answer

 
discard

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.