Reputation: 1147
Input variable contains:
key1-key2-key3_command
Output needs to be:
command -k key1 -k key2 -k key3
Caveat: Number of keys can vary from 1 to 3.
I've counted the number of dashes and use that with an if statement to create a Boolean indicator for each key (ie. key1=1, unset key2). Then I was going to use something like ${parameter:+word}
to add in the key if the flag for that key is set. It started getting a bit messy so I thought I'd ask here on what the best way to achieve this would be.
Upvotes: 2
Views: 89
Reputation: 361739
var='key1-key2-key3_command'
IFS=_ read -r keys command <<< "$var" # Split $var at underscores.
IFS=- read -ra keys <<< "$keys" # Split $keys at dashes, -a to save as array.
for key in "${keys[@]}"; do # Treat $command as an array and add
command+=(-k "$key") # -k arguments to it.
done
echo "${command[@]}"
Notes:
$IFS
are only temporary; they don't affect subsequent commands."${command[@]}"
(no echo).Upvotes: 5
Reputation: 246877
Runs in a subshell to avoid polluting the current IFS and positional params
(
IFS="-_"
set -- $var
command=("${!#}")
while [[ "$1" != "${command[0]}" ]]; do
command+=(-k "$1")
shift
done
echo "${command[@]}"
)
Remove "echo" to execute.
Upvotes: 0
Reputation: 9206
echo "key1-key2-key3_command" | sed -r 's/(.*?)-(.*?)-(.*?)_(.*?)/\4 -k \1 -k \2 -k \3/g'
command -k key1 -k key2 -k key3
Upvotes: 1