简体   繁体   中英

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 ".

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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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