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

查看:22
本文介绍了数组上的 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 的 wiki 在这里提供了帮助:

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