2

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.

3 Answers 3

5
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:

  • This handles an arbitrary number of keys.
  • Handles keys with whitespace in them.
  • The changes to $IFS are only temporary; they don't affect subsequent commands.
  • If you want to execute the command, change the last line to simply "${command[@]}" (no echo).
Sign up to request clarification or add additional context in comments.

Comments

1
echo "key1-key2-key3_command" | sed -r 's/(.*?)-(.*?)-(.*?)_(.*?)/\4 -k \1 -k \2 -k \3/g'
command -k key1 -k key2 -k key3

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.