简体   繁体   English

如何在BASH的一行中打印两个数组变量

[英]how to print two array variables in a line in BASH

I tried this code in my shell script in ubuntu 12.04 bash 我在Ubuntu 12.04 bash的shell脚本中尝试了此代码

IFS=$'\t'
name=(one two three four five)
fam=($(seq -s" " 1 1 5))
for (i=0;i<5;i++) 
do 
  printf "%s\t%s\n" ${fam[i]} ${name[i]} 
done

The output I want is like that 我想要的输出是这样的

1 one
2 two
3 three
4 four
5 five

But the really output is 但是真正的输出是

1 2 3 4 5   one
two 
three   
four    
five

What went wrong in my code? 我的代码出了什么问题? and how to print more than one array variable in a line just using one loop? 以及如何仅使用一个循环就在一行中打印多个数组变量?

name=(one two three four five)
fam=(1 2 3 4 5)

for i in ${!name[*]}
do
  printf '%s %s\n' ${fam[i]} ${name[i]}
done

or you can just fix 或者你可以解决

for  (i = 0; i < 5; i++)
for ((i = 0; i < 5; i++))

When you set IFS to '\\t' it causes the array initializer to break the input on tabs so you get '1 2 3 4 5' assigned to fam[0]. 当您将IFS设置为'\\ t'时,它将导致数组初始化程序中断制表符上的输入,因此您将分配给fam [0]的'1 2 3 4 5'。 You need to change the seq delimiter to match. 您需要更改seq分隔符以匹配。

fam=($(seq -s $'\t' 1 1 5))

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

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