How can I read lines from the standard input into an array and then concatenate the array with itself?

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

3 Answers

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

readarray -t countries 

...or, with older versions of 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[@]}" ) 
3

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.

2

on ubuntu 14.04, the following would concatenate three elements (an element count would give :3), each element being an array 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).

3

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.