bash 如何在bash中连接数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31143874/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 22:01:36  来源:igfitidea点击:

How to concatenate arrays in bash?

arraysbashconcatenation

提问by Enamul Hassan

I am a new to Bash. I have an array taking input from standard input. I have to concatenate itself twice. Say, I have the following elements in the array:

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

Namibia
Nauru
Nepal
Netherlands
NewZealand
Nicaragua
Niger
Nigeria
NorthKorea
Norway

Now, The output should be:

现在,输出应该是:

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

My code is:

我的代码是:

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[@]}"

Note that, I can print it thrice like the code below, but it is not my motto. I have to concatenate them in the array.

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

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

回答by Charles Duffy

First, to read your list into an array, one entry per line:

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

readarray -t countries

...or, with older versions of bash:

...或者,使用旧版本的 bash:

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


Second, to duplicate the entries, either expand the array to itself three times:

其次,要复制条目,请将数组扩展为自身三倍:

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

...or use the modern syntax for performing an append:

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

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

回答by Amit24x7

Simply write this:

简单写下:

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

The first line is to take input array, second to concatenate and last to print the array.

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

回答by Jerome

on ubuntu 14.04, the following would concatenate three elements (an element count would give :3), each element being an array countries:

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

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

while the below would concatenate all elements in one single array:

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

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

a count of this would be 30 (taken into account the countries specified in the original post).

计数为 30(考虑到原始帖子中指定的国家/地区)。