![](/img/trans.png)
[英]How to execute Terminal commands from a shell script? (MacOS 10.12)
[英]URL encode a string in macOS terminal or shell script
我需要 URL 在 macOS 終端或 shell 腳本中編碼 unix 文件路徑,以便將其作為輸入:
"/Volumes/Macintosh HD/Music/1-01 デ ジタルライフ.mp3"
我得到的是 output:
"file:///Volumes/Macintosh%20HD/Music/1-01%20%E3%83%86%E3%82%99%E3%82%B7%E3%82%99%E3%82%BF%E3%83%AB%E3%83%A9%E3%82%A4%E3%83%95.mp3"
基本上與在瀏覽器 window 中拖動所述文件然后復制其 URL 相同。我該如何實現? 謝謝。
可能有更好的方法來做到這一點,但我最終設法做到了這一點:
printf %s "/Volumes/Macintosh HD/Music/1-01 デ ジタルライフ.mp3" |
curl -Gso /dev/null -w %{url_effective} --data-urlencode @- "" | #urlencoding
cut -c3- | #cut the "/?" at the beginning
sed 's=%2F=\/=g' | #change "%2F" back to slash
sed 's=+=%20=g' | #replace "+" to urlencoded space (%20)
sed 's=^=file:\/\/=' #prepend "file://"
結果:
"file:///Volumes/Macintosh%20HD/Music/1-01%20%E3%83%86%E3%82%99%E3%82%B7%E3%82%99%E3%82%BF%E3%83%AB%E3%83%A9%E3%82%A4%E3%83%95.mp3"
我們可以在perl
中use URI
,由此將 URI object 自動轉換為字符串恰好完成了所需的操作(除了file://
,它可以簡單地放在前面):
perl -e 'use URI;print "file://".URI->new("/Volumes/Macintosh HD/Music/1-01 デ ジタルライフ.mp3");'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.