3

So I have Name age and city data:

name=(Alex Barbara Connor Daniel Matt Peter Stan)
age=(22 23 55 32 21 8 89)
city=(London Manchester Rome Alberta Naples Detroit Amsterdam)

and I want to set up the following as 3 column data with the headings Name Age and city, I can easily get the first column using

touch info.txt
echo "Name Age City" > info.txt
for n in ${name[@]}; do
    echo $n >> info.txt
done

but I can't figure how to get the rest of the data, and I can't seem to find anywhere on how to add data that's different as a new column.

Any help would be greatly appreciated, thank you.

3 Answers3

3

Try something like this:

name=(Alex Barbara Connor Daniel Matt Peter Stan)
age=(22 23 55 32 21 8 89)
city=(London Manchester Rome Alberta Naples Detroit Amsterdam)

touch info.txt
echo "Name Age City" > info.txt
for n in $(seq 0 6); do
    echo ${name[$n]} ${age[$n]} ${city[$n]} >> info.txt
done

Output in info.txt:

Name Age City
Alex 22 London
Barbara 23 Manchester
Connor 55 Rome
Daniel 32 Alberta
Matt 21 Naples
Peter 8 Detroit
Stan 89 Amsterdam
JoseLinares
  • 775
  • 5
  • 15
1

You can fix a specific width for each column (here 20 is used)

name=(Alex Barbara Connor Daniel Matt Peter Stan)
age=(22 23 55 32 21 8 89)
city=(London Manchester Rome Alberta Naples Detroit Amsterdam)

for i in "${!name[@]}"; do
    printf "%-20s %-20s %-20s\n" "${name[i]}" "${age[i]}" "${city[i]}"
done

Output:

Alex                 22                   London              
Barbara              23                   Manchester          
Connor               55                   Rome                
Daniel               32                   Alberta             
Matt                 21                   Naples              
Peter                8                    Detroit             
Stan                 89                   Amsterdam 
Aven Desta
  • 2,114
  • 12
  • 27
1

JoseLinares solved your problem. For your information, here is a solution with the paste command whose purpose is exactly that: putting data from different sources in separate columns.

$ printf 'Name\tAge\tCity\n'
$ paste <(printf '%s\n' "${name[@]}") \
        <(printf '%3d\n' "${age[@]}") \
        <(printf '%s\n' "${city[@]}")

Name    Age City
Alex     22 London
Barbara  23 Manchester
Connor   55 Rome
Daniel   32 Alberta
Matt     21 Naples
Peter     8 Detroit
Stan     89 Amsterdam

xhienne
  • 5,738
  • 1
  • 15
  • 34