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:
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[@]}"
In order to combine (concatenate) two arrays, we find its length stored in aLen and bLen respectively. Then, we create a new integer array result with length aLen + bLen . Now, in order to combine both, we copy each element in both arrays to result by using arraycopy() function.
To append element(s) to an array in Bash, use += operator. This operator takes array as left operand and the element(s) as right operand. The element(s) must be enclosed in parenthesis. We can specify one or more elements in the parenthesis to append to the given array.
Another way of concatenating string data in bash is by using shorthand (+=) operator. Create a file named 'concat3.sh' and add the following code to check the use of shorthand operator. Here, the shorthand operator, '+=' is used inside a 'for' loop to combine the elements of a list.
How to Echo a Bash Array? To echo an array, use the format echo ${Array[0]}. Array is your array name, and 0 is the index or the key if you are echoing an associative array. You can also use @ or * symbols instead of an index to print the entire array.
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[@]}" )
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With