'How do I print out 2 separate arrays with new lines in bash script
So basically I want to be able to print out 2 separate arrays with newlines between each element.
Sample output I'm looking for:
a x
b y
(a,b being apart of one array x,y being a separate array)
Currently im using:
printf "%s\n" "${words[@]} ${newWords[@]}"
But the output comes out like:
a
b x
y
Solution 1:[1]
As bash is tagged, you could use paste from GNU coreutils with each array as an input:
$ words=(a b)
$ newWords=(x y)
$ paste <(printf '%s\n' "${words[@]}") <(printf '%s\n' "${newWords[@]}")
a x
b y
TAB is the default column separator but you can change it with option -d.
If you have array items that might contain newlines, you can switch to e.g. NUL-delimited strings by using the -z flag and producing each input using printf '%s\0'.
Solution 2:[2]
What does "${words[@]} ${newWords[@]}" produce? Let's put that expansion into another array and see what's inside it:
words=(a b)
newWords=(x y)
tmp=("${words[@]} ${newWords[@]}")
declare -p tmp
declare -a tmp=([0]="a" [1]="b x" [2]="y")
So, the last element of the first array and the first element of the second array are joined as a string; the other elements remain individual.
paste with 2 process substitutions is a good way to solve this. If you want to do it in plain bash, iterate over the indices of the arrays:
for idx in "${!words[@]}"; do
printf '%s\t%s\n' "${words[idx]}" "${newWords[idx]}"
done
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | pmf |
| Solution 2 |
