如何切在bash数组 [英] How to slice an array in bash

查看:209
本文介绍了如何切在bash数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(编辑以适合的答案)

展望了阵列一节中在bash(1)手册页,我没有找到一个方法来切一个bash数组。

Looking the "Array" section in the bash(1) man page, I didn't find a way to slice a bash array.

于是我想出了这个过于复杂的功能:

So I came up with this overly complicated function:

#!/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

有没有更好的方式来做到这一点?

Is there a better way to do that?

推荐答案

查看的参数扩展在Bash节页。 A [@] 返回数组的内容,:1:2 需要长度为2片,开始索引1

See the Parameter Expansion section in the Bash man page. A[@] returns the contents of the array, :1:2 takes a slice of length 2, starting at index 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是一个数组元素(和它包含一个额外的空格)是preserved。

Note that the fact that "a b c" is one array element (and that it contains an extra space) is preserved.

这篇关于如何切在bash数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆