2

输入变量包含:

key1-key2-key3_command

输出需要:

command -k key1 -k key2 -k key3

警告:键的数量可以从 1 到 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.

4

3 回答 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[@]}"

笔记:

  • 这可以处理任意数量的键。
  • 处理带有空格的键。
  • 更改$IFS只是暂时的;它们不会影响后续命令。
  • 如果要执行命令,请将最后一行更改为简单"${command[@]}"(无回显)。
于 2013-01-15T20:35:12.970 回答
1
echo "key1-key2-key3_command" | sed -r 's/(.*?)-(.*?)-(.*?)_(.*?)/\4 -k \1 -k \2 -k \3/g'
command -k key1 -k key2 -k key3
于 2013-01-15T20:28:51.790 回答
0

在子外壳中运行以避免污染当前的 IFS 和位置参数

( 
    IFS="-_"
    set -- $var
    command=("${!#}")
    while [[ "$1" != "${command[0]}" ]]; do 
        command+=(-k "$1")
        shift
    done
    echo "${command[@]}"
)

删除“回声”执行。

于 2013-01-15T21:50:45.773 回答