数组上的Shell参数扩展 [英] Shell parameter expansion on arrays

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

问题描述

假设我将一些数据读入Bash数组:

Say I read some data into a Bash array:

$ IFS=" " read -a arr <<< "hello/how are/you iam/fine/yeah"

现在,我要为数组中的每个元素打印第一个/切片字段.

Now, I want to print the first /-sliced field for each element in the array.

我要做的是遍历元素,并使用shell参数扩展从第一个/中剥离所有内容:

What I do is to loop over the elements and use shell parameter expansion to strip everything from the first /:

$ for w in "${arr[@]}"; do echo "${w%%/*}"; done
hello
are
iam

但是,由于printf允许我们在单个表达式中打印数组的全部内容:

However, since printf allows us to print the whole content of the array in a single expression:

$ printf "%s\n" "${arr[@]}"
hello/how
are/you
iam/fine

...我想知道是否有一种方法可以在使用printf时使用shell参数扩展${w%%/*},而不是循环遍历所有元素并针对每个元素进行处理.

... I wonder if there is a way to use the shell parameter expansion ${w%%/*} at the time of using printf, instead of looping over all the elements and doing it against every single one.

推荐答案

哦,我找到了方法:正常使用参数扩展,只针对${arr[@]}而不是${arr}

Oh, I just found the way: just use the parameter expansion normally, only that against ${arr[@]} instead of ${arr}!

$ IFS=" " read -a arr <<< "hello/how are/you iam/fine/yeah"
$ printf "%s\n" "${arr[@]%%/*}"
hello
are
iam

格雷格的维基在这里提供帮助:

Greg's wiki helped here:

数组上的参数扩展

BASH阵列非常灵活,因为它们集成良好 与其他外壳扩展.任何可以扩展的参数 在标量或单个数组元素上执行的操作同样可以适用 到整个数组或一组位置参数,以使所有 成员可以立即扩展,可能需要执行其他操作 映射到每个元素.

BASH arrays are remarkably flexible, because they are well integrated with the other shell expansions. Any parameter expansion that can be carried out on a scalar or individual array element can equally apply to an entire array or the set of positional parameters such that all members are expanded at once, possibly with an additional operation mapped across each element.

$ a=(alpha beta gamma)  # assign to our base array via compound assignment
$ echo "${a[@]#a}"      # chop 'a' from the beginning of every member
lpha beta gamma
$ echo "${a[@]%a}"      # from the end
alph bet gamm
$ echo "${a[@]//a/f}"   # substitution
flphf betf gfmmf

这篇关于数组上的Shell参数扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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