4

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?

sashoalm
  • 75,001
  • 122
  • 434
  • 781

5 Answers5

5

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
anubhava
  • 761,203
  • 64
  • 569
  • 643
2

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.

The Archetypal Paul
  • 41,321
  • 20
  • 104
  • 134
2

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.

choroba
  • 231,213
  • 25
  • 204
  • 289
1

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=%..

How to decode URL-encoded string in shell?

Community
  • 1
  • 1
Zombo
  • 1
  • 62
  • 391
  • 407
1

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/НА БЪЛГАРСКИ
Evgeny
  • 11
  • 3