Home > OS >  How do I print out 2 separate arrays with new lines in bash script
How do I print out 2 separate arrays with new lines in bash script

Time:02-28

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

CodePudding user response:

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'.

CodePudding user response:

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
  • Related