0

I am working on a wit.ai project and I want the user to be able to type a query/request in plain human readable text (e.g "Turn on the lights") and the program will convert it to a formatted version designed to be put in a curl request (e.g "Turn%20on%20the%20lights").

How would I for example turn "Stack Exchange" into "Stack%20Exchange" using tools in bash?

Léa Gris
  • 17,497
  • 4
  • 32
  • 41

2 Answers2

2

Not really a basic shell tool but I've used jq for the job:

$ echo -n "Stack exchange" | jq -sRr @uri
Stack%20exchange%0A

To get rid of the %0A use echo -n, naturally.

James Brown
  • 36,089
  • 7
  • 43
  • 59
  • 1
    `echo -n` is non-standard, so this instead: `printf 'Stack exchange' | jq -sRr @uri`. Or even better: `jq -nRr --arg s 'Stack exchange' '$s|@uri'` saving an unnecessary sub-shell. – Léa Gris Nov 28 '20 at 12:55
0
read -e a # read from the keyboard interactively into the variable `a`
sed 's/ /%20/g' <<<$a # replace spaces to "$20" in `a` with the command `sed` and print it

or

echo $a |sed 's/ /%20/g'

If you want to put it into a variable:

b=$(sed 's/ /%20/g' <<<$a)
Michael
  • 5,095
  • 2
  • 13
  • 35