(编辑适合答案)
查看bash(1)手册页中的“Array”部分,我没有找到一种方法来切割bash数组。
所以我想出了这个过于复杂的功能:
- #!/bin/bash
- # @brief: slice a bash array
- # @arg1: output-name
- # @arg2: input-name
- # @args: seq args
- # ----------------------------------------------
- function slice() {
- local output=$1
- local input=$2
- shift 2
- local indexes=$(seq $*)
- local -i i
- local tmp=$(for i in $indexes
- do echo "$(eval echo \"\${$input[$i]}\")"
- done)
- local IFS=$'\n'
- eval $output="( \$tmp )"
- }
使用像这样:
- $ A=( foo bar "a b c" 42 )
- $ slice B A 1 2
- $ echo "${B[0]}" # bar
- $ echo "${B[1]}" # a b c
有更好的方法吗?
请参见Bash手册页中的
Parameter Expansion部分。 A [@]返回数组的内容,:1:2采用长度为2的切片,从索引1开始。
- A=( foo bar "a b c" 42 )
- B=("${A[@]:1:2}")
- C=("${A[@]:1}") # slice to the end of the array
- echo "${B[@]}" # bar a b c
- echo "${B[1]}" # a b c
- echo "${C[@]}" # bar a b c 42
注意,“a b c”是一个数组元素(并且它包含额外的空间)的事实被保留。