spizzak
spizzak

Reputation: 1147

Parse bash variable for command and command options

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

Answers (3)

John Kugelman
John Kugelman

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:

  • 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).

Upvotes: 5

glenn jackman
glenn jackman

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

Adam Sznajder
Adam Sznajder

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

Related Questions