Home > Software design >  URL encode a string in macOS terminal or shell script
URL encode a string in macOS terminal or shell script

Time:01-29

I need to URL encode a unix file path in macOS terminal or shell script so that with this as input:

"/Volumes/Macintosh HD/Music/1-01 デ ジタルライフ.mp3"

I get this as output:

"file:///Volumes/Macintosh HD/Music/1-01 デジタルライフ.mp3"

basically the same as dragging said file in a browser window and then copying its URL. how can I achieve this? Thanks.

CodePudding user response:

There are probably better ways of doing it but I finally managed to do it this way:

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=/=\/=g' | #change "/" back to slash
sed 's= = =g' | #replace " " to urlencoded space ( )
sed 's=^=file:\/\/=' #prepend "file://"

Result:

"file:///Volumes/Macintosh HD/Music/1-01 デジタルライフ.mp3"
  • Related