简体   繁体   English

Bash成对数组扩展

[英]Bash pairwise array expansion

I have two arrays of same lengths like following: 我有两个相同长度的数组,如下所示:

arr1[1]=2
arr1[2]=5

arr2[1]=x
arr2[2]=y

I am trying to create a string like " 2 x 5 y ". 我正在尝试创建一个类似“ 2 x 5 y ”的字符串。

Since the length of the arrays can be a variable, is there any way to do this without using a loop and string concatenation (like parameter expansion or something) ? 由于数组的长度可以是一个变量,是否可以在不使用循环和字符串串联的情况下(例如,参数扩展之类的东西)进行任何操作?

You can use paste with process substitution : 您可以在流程替换中使用paste

arr1[1]=2
arr1[2]=5

arr2[1]=x
arr2[2]=y

s=$(paste <(printf "%s\n" "${arr1[@]}") <(printf "%s\n" "${arr2[@]}") |
    tr '[[:space:]]' ' ')
echo "$s"
2 x 5 y

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM