Reputation: 1431
I have a variable
some_var="a23=some value&p44=another_value&uw=possibly_another one"
and I want to convert it into several substrings one for each =
(breaking at the &
). So I would get
a23=some value
p44=another_value
uw=possibly_another one
If I run this code
for s in ${some_var//&/ };do echo $s;done
I get however
a23=some
value
p44=another_value
uw=possibly_another
one
(it breaks at the empty spaces)
How can I run the loop so that it takes space into account?
Upvotes: 3
Views: 305
Reputation: 10113
read
into an array using the '&' as field separator:
#!/bin/bash
some_var='a23=some value&p44=another_value&uw=possibly_another one'
IFS='&' read -r -a arr <<< "$some_var"
for s in "${arr[@]}"; do
printf '%s\n' "$s"
done
A technique similar to yours also would work:
(IFS='&'; for s in $some_var; do printf '%s\n' "$s"; done)
Notice that it runs in a subshell not to mess up with the IFS
of the current shell.
You may consider reading this article for detailed information on IFS
.
Upvotes: 4
Reputation: 19545
Populating an associative array with the argument=value pairs:
#!/usr/bin/env bash
uri_argstring='a23=some value&p44=another_value&uw=possibly_another one'
# Declare an empty associative array
declare -A uri_args=()
# Populate the associative array by reading key values pairs
# delimiting field by &, = or newline,
# delimiting records (argument=value or key=value pairs) with & or End Of File
while IFS=$'=&\n' read -r -d '&' k v; do
# Add entry to associative array
uri_args[$k]=$v
done <<<"$uri_argstring" # Feed here-string to the while loop reading
# Fancy printing
printf 'Argument=Value\n--------------\n'
# Iterate the keys from the uri_args associative array
for arg in "${!uri_args[@]}"; do
value=${uri_args[$arg]}
# Printout
printf '%s=%s\n' "$arg" "$value"
done
Output:
Argument=Value
--------------
a23=some value
p44=another_value
Upvotes: 4