Categories
Server

Add urldecode to your command line.

So, here’s the deal:

alias urldecode='sed "s@+@ @g;s@%@\\x@g" | xargs -0 printf "%b"'

This command is an alias—a shorthand that saves me from typing a long series of commands every time I need to decode a URL. Think of it as me saying, “Yo terminal, whenever I type urldecode, just run this whole thing for me.” But what does it actually do?

The Problem We’re Solving

You’ve seen those ugly URLs with %20 for spaces or %3A for colons? Yeah, decoding those by hand is no fun. So, instead of decoding each character one by one, I use this alias to automate it.

Here’s the breakdown:

  1. sed "s@+@ @g;s@%@\\\\x@g"
    • sed is a stream editor that we use to make text transformations.
    • First, this part: s@+@ @g replaces every + in the URL with a space (@ is just a delimiter here, replacing the default /). Because in URLs, + is used for spaces. Handy, right?
    • Then, we’ve got s@%@\\\\x@g, which is the magical part that takes all those %xx patterns (URL encoding) and transforms them into something printf can understand. Specifically, \\\\x turns each %xx into \x, which is the escape code format for hex in printf.
  2. xargs -0 printf "%b"
    • This takes the output from sed and passes it to printf. The xargs -0 part ensures that the input is handled correctly, particularly if there are null characters. It’s super useful if your URL is complex or has tricky characters in it.
    • printf "%b" is where the actual decoding magic happens. %b tells printf to interpret backslash escapes, so our \x becomes an actual decoded character. Ta-da!

So What Happens When You Run It?

When you run something like this:

echo "https%3A%2F%2Fexample.com%2Fsearch%3Fq%3Dnyc+coffee" | urldecode

It gets transformed from this gobbledygook:

https%3A%2F%2Fexample.com%2Fsearch%3Fq%3Dnyc+coffee

To this nice, human-readable format:

https://example.com/search?q=nyc coffee

Geeky Tips:

  • If you’re regularly working with URLs and encoded strings (maybe you’re doing some web scraping or API work?), this alias can save you tons of time.
  • You can add this to your ~/.bashrc or ~/.zshrc to have it always ready when you open a terminal. Just paste the line there and run source ~/.bashrc (or source ~/.zshrc).