I have a percent encoded file URL - for example file:///home/sashoalm/Has%20Spaces.txt
. I need to convert it to a local file - /home/sashoalm/Has Spaces.txt
.
How can I do that in bash?
In BASH you can use this utility function:
decodeURL() {
printf "$(sed 's#^file://##;s/+/ /g;s/%\(..\)/\\x\1/g;' <<< "$@")\n";
}
Then call this function as:
decodeURL 'file:///home/sashoalm/Has%20Spaces.txt'
/home/sashoalm/Has Spaces.txt
Urlencode should do it (-d option)
-d Do URL-decoding rather than encoding, according to RFC 1738. %HH and %hh strings are converted and other characters are passed through unmodified, with the exception that + is converted to space.
Perl to the rescue:
echo file:///home/sashoalm/Has%20Spaces.txt |\
perl -MURI -MURI::Escape -lne \
'print uri_unescape(URI->new($_)->path)'
See URI and URI::Escape.
GNU awk
#!/usr/bin/awk -fn
@include "ord"
BEGIN {
RS = "%.."
}
{
printf RT ? $0 chr("0x" substr(RT, 2)) : $0
}
Or
#!/bin/sh
awk -niord '{printf RT?$0chr("0x"substr(RT,2)):$0}' RS=%..
Using GIO binary for different locales (Bulgarian for example):
LC_MESSAGES=C gio info file:///home/user/%D0%9D%D0%90%20%D0%91%D0%AA%D0%9B%D0%93%D0%90%D0%A0%D0%A1%D0%9A%D0%98|grep "local path:"|sed 's/^[^/]*//'
Result (localized):
/home/user/НА БЪЛГАРСКИ