如何在 Bash 中对数组进行切片 [英] How to slice an array in Bash

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

问题描述

查看 bash(1) 手册页中的数组"部分,我没有找到对数组进行切片的方法.

Looking the "Array" section in the bash(1) man page, I didn't find a way to slice an 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 this?

推荐答案

参见 man 页面中的 rel="noreferrer">参数扩展 部分.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
echo "${C[@]: -2:2}"  # a  b c 42 # The space before the - is necesssary

请注意,a b c 是一个数组元素(并且它包含一个额外的空格)这一事实被保留.

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天全站免登陆