数组上的Shell参数扩展

前端之家收集整理的这篇文章主要介绍了数组上的Shell参数扩展前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
假设我将一些数据读入Bash数组:
$IFS=" " read -a arr <<< "hello/how are/you iam/fine/yeah"

现在,我想为数组中的每个元素打印第一个/ -sliced字段.

我所做的是遍历元素并使用shell参数扩展来从第一个/中删除所有内容

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

但是,由于printf允许我们在一个表达式中打印数组的整个内容

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

…我想知道在使用printf时是否有办法使用shell参数扩展${w %% / *},而不是循环遍历所有元素并对每一个元素进行操作.

哦,我刚刚找到了方法:正常使用参数扩展,只针对${arr [@]}而不是${arr}!
$IFS=" " read -a arr <<< "hello/how are/you iam/fine/yeah"
$printf "%s\n" "${arr[@]%%/*}"
hello
are
iam

格雷格的维基帮助了这里:

07000

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

06001

猜你在找的Bash相关文章