繁体   English   中英

如何在bash中连接数组?

[英]How to concatenate arrays in bash?

我是Bash的新手。 我有一个数组从标准输入中获取输入。 我必须连接两次。 说,我在数组中有以下元素:

Namibia
Nauru
Nepal
Netherlands
NewZealand
Nicaragua
Niger
Nigeria
NorthKorea
Norway

现在,输出应该是:

Namibia Nauru Nepal Netherlands NewZealand Nicaragua Niger Nigeria NorthKorea Norway Namibia Nauru Nepal Netherlands NewZealand Nicaragua Niger Nigeria NorthKorea Norway

我的代码是:

countries=()
while read -r country; do
    countries+=( "$country" )
done
countries=countries+countries+countries # this is the wrong way, i want to know the right way to do it
echo "${countries[@]}"

请注意,我可以像下面的代码一样打印三次,但这不是我的座右铭。 我必须在数组中连接它们。

countries=()
while read -r country; do
    countries+=( "$country" )
done
echo "${countries[@]} ${countries[@]} ${countries[@]}"

首先,要将列表读入数组,每行一个条目:

readarray -t countries

...或者,对于旧版本的bash:

# same, but compatible with bash 3.x; || is to avoid non-zero exit status.
IFS=$'\n' read -r -d '' countries || (( ${#countries[@]} ))

其次,要复制条目,要么将数组展开为自身三次:

countries=( "${countries[@]}" "${countries[@]}" "${countries[@]}" )

...或使用现代语法执行追加:

countries+=( "${countries[@]}" "${countries[@]}" )

只需写下:

countries=$(cat)
countries+=( "${countries[@]}" "${countries[@]}" )
echo ${countries[@]}

第一行是输入数组,第二行是连接,最后是打印数组。

在ubuntu 14.04上,以下将连接三个元素(元素计数将给出:3),每个元素是一个数组countries

countries=( "${countries[@]}" "${countries[@]}" "${countries[@]}" )

而下面将连接一个单独数组中的所有元素:

countries=( ${countries[*]} ${countries[*]} ${countries[*]} )

计数为30(考虑到原帖中指定的国家)。

暂无
暂无

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

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