Skip to content

Instantly share code, notes, and snippets.

@sergeiwaigant
Last active April 11, 2025 17:47
Show Gist options
  • Save sergeiwaigant/f0cf816e143114b6a7d81a901b5d3ce6 to your computer and use it in GitHub Desktop.
Save sergeiwaigant/f0cf816e143114b6a7d81a901b5d3ce6 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'
@SaeedDev94
Copy link

Maybe a shorter version:

echo 'encode this' | jq -Rr @uri

@silverwind
Copy link

Maybe a shorter version:

echo 'encode this' | jq -Rr @uri

Better use printf because echo appends a possibly unwanted \n at the end.

@chinkung
Copy link

chinkung commented Apr 2, 2025

Normally I do this

echo -n 'encode this' | jq -Rr @uri

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment