Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ryanvgates/b81d34724489eb894f357263522ff669 to your computer and use it in GitHub Desktop.
Save ryanvgates/b81d34724489eb894f357263522ff669 to your computer and use it in GitHub Desktop.
Simply URL encode string with Linux/Bash/Shell tools

Reference https://stackoverflow.com/a/34407620/13287790

$ printf %s 'encode this'|jq -sRr @uri
encode%20this
$ jq -rn --arg x 'encode this' '$x|@uri'
encode%20this
-r (--raw-output) outputs the raw contents of strings instead of JSON string literals. -n (--null-input) doesn't read input from STDIN.

-R (--raw-input) treats input lines as strings instead of parsing them as JSON, and -sR (--slurp --raw-input) reads the input into a single string. You can replace -sRr with -Rr if your input only contains a single line, or if you don't want to replace linefeeds with %0A:

$ printf %s\\n 'multiple lines' 'of text'|jq -Rr @uri
multiple%20lines
of%20text
$ printf %s\\n 'multiple lines' 'of text'|jq -sRr @uri
multiple%20lines%0Aof%20text%0A
Or this percent-encodes all bytes:

xxd -p|tr -d \\n|sed 's/../%&/g'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment