Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Is there any tool to urldecode a file's name and replace it?

Example:

$ ls
hello%20world.txt
$ urldecode *.txt
$ ls
hello world.txt
share|improve this question
add comment

3 Answers

up vote 0 down vote accepted

A new blog post covers this with echo(1) and printf(1).

urldecode() {
  arg="$1"
  i="0"
  while [ "$i" -lt ${#arg} ]; do
    c0=${arg:$i:1}
    if [ "x$c0" = "x%" ]; then
      c1=${arg:$((i+1)):1}
      c2=${arg:$((i+2)):1}
      printf "\x$c1$c2"
      i=$((i+3))
    else
      echo -n "$c0"
      i=$((i+1))
    fi
  done
}
share|improve this answer
add comment

sed and echo can help out like so:

$ echo -n -e "$(echo hello%20world+ok | sed 's/+/ /g;s/%\(..\)/\\x\1/g;')"
hello world ok


Edit: Per SamB's comment:

$ ls *.txt
hello%20%20world++ok?.txt
$ for file in *.txt; do 
>   mv "${file}" "$(echo -n -e "$(echo "${file}" | sed 's/+/ /g;s/%\(..\)/\\x\1/g;')")"; 
> done
$ ls *.txt
hello  world  ok?.txt
share|improve this answer
    
The idea here is to turn '+'s into spaces directly, and turn % signs into '\x' escapes, and then let echo interpret the \x escapes using the '-e' option. Try running "echo -e 'hello\x20world'" to see this in action. –  Suppressingfire Nov 29 '09 at 15:35
    
How about the part where it renames the file(s)? –  SamB Jun 1 '10 at 1:11
    
@SamB: left as an exercise for the reader :-) –  Suppressingfire Jun 16 '10 at 20:29
add comment

I think this Perl snippet can be used as a base for what you are looking for.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.