在bash中将文件路径转换为URI

Glu*_*ate 13 bash filenames

如何在命令行中将文件路径转换为 ​​URI?

示例

/home/MHC/directory with spaces and ümläuts
Run Code Online (Sandbox Code Playgroud)

file:///home/MHC/directory%20with%20spaces%20and%20%C3%BCml%C3%A4uts
Run Code Online (Sandbox Code Playgroud)

Glu*_*ate 5

一种方法是使用urlencode(通过 将其安装在 Ubuntu 上sudo apt-get install gridsite-clients)。

urlencode -m "$filepath"
Run Code Online (Sandbox Code Playgroud)

将路径转换为 ​​URI。URI 的“file://”部分将被省略,但您可以通过 bash one-liner 轻松添加它:

uri=$(urlencode -m "$1"); echo "file://$uri"
Run Code Online (Sandbox Code Playgroud)

或直接

echo "file://$(urlencode -m "$1")"
Run Code Online (Sandbox Code Playgroud)

或者

echo -n file://; urlencode -m "$1"
Run Code Online (Sandbox Code Playgroud)

非常感谢 Michael Kjörling 提供的参考资料!


小智 5

您还可以直接从命令行使用 Perl 模块URI::file :

\n\n
$ path="/home/MHC/directory with spaces and \xc3\xbcml\xc3\xa4uts"\n$ echo $path | perl -MURI::file -e \'print URI::file->new(<STDIN>)."\\n"\'\nfile:///home/MHC/directory%20with%20spaces%20and%20%C3%BCml%C3%A4uts\n$\n
Run Code Online (Sandbox Code Playgroud)\n


Roc*_*ite 5

在 CentOS 上,不需要额外的依赖:

$ python -c "import urllib;print urllib.quote(raw_input())" <<< "$my_url"
Run Code Online (Sandbox Code Playgroud)