BashでファイルパスをURIに変換する

BashでファイルパスをURIに変換する

コマンドラインでファイルパスをURIに変換する方法は?

はい:

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

到着

file:///home/MHC/directory%20with%20spaces%20and%20%C3%BCml%C3%A4uts

答え1

1つの方法は使用することですurlencode(Ubuntuにインストールしてsudo apt-get install gridsite-clients)。

urlencode -m "$filepath"

パスをURIに変換します。 URIの「file://」部分は省略されますが、bash 1行で簡単に追加できます。

uri=$(urlencode -m "$1"); echo "file://$uri"

または直接

echo "file://$(urlencode -m "$1")"

または

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

参考にしたMichael Kjörlingに感謝します!

答え2

CentOSでは追加の依存関係は必要ありません。

$ python -c "import urllib;print urllib.quote(raw_input())" <<< "$my_url"

答え3

Perlモジュールを使用することもできます。URI::ファイルコマンドラインから直接:

$ 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
$

答え4

次のスクリプトにパスをパラメータとして渡すことができます。

#!/usr/bin/env gjs

const { Gio } = imports.gi;

let path = Gio.File.new_for_path(ARGV[0]);
let uri = path.get_uri();
print(uri);

uri をパスに変換するには、次のスクリプトを使用します。

#!/usr/bin/env gjs

const { Gio } = imports.gi;

let uri = Gio.File.new_for_uri(ARGV[0]);
let path = uri.get_path();
print(path);

関連情報