coyk
coyk

Reputation: 11

Printing array with printf vs echo gives different results

I am trying to create an array from a file. In the troubleshooting process, I hope to print out all elements of the array to convince myself I'm doing it correctly. However, when I use a hard coded array vs an array constructed from a file, I get different results when trying to output all the array elements.

When I hard code an array like this:

matches=("SviPEND18C_0002" "SviPEND18C_0006")

To get output, I use:

echo "${matches[@]}"

which gives me

SviPEND18C_0002 SviPEND18C_0006

And when I use:

printf '%s\n' "${matches[@]}"

I get:

SviPEND18C_0002
SviPEND18C_0006

All that makes sense to me. However, when I try to make an array from a file and get the output, I don't understand the results. I have a text file (L0316_F.txt) with a single column of sample names, like in the matches array above, but with 50 total. Here's how I put them into an array

mapfile -t IDfemales < <(awk '{print $1}' ../L0316_F.txt)

Now when I use echo as above:

echo "${IDfemales[@]}"

I get the last element of the array only. I was expecting all 50 elements on a single line.

echo "${IDfemales}"

I get the first element of the array only.

However, when I use printf as above:

printf '%s\n' "${IDfemales[@]}"

I get all 50 elements, 1 element per line.

I have already looked at https://stackoverflow.com/questions/41150814/how-to-echo-all-values-from-array-in-bash and I don't get the same results they do.

I would love an explanation. Eventually, I plan to match the elements in the array to file names, which isn't working for me right now, and I assume it's because I don't understand how the array is stored.

Upvotes: 1

Views: 69

Answers (1)

L&#233;a Gris
L&#233;a Gris

Reputation: 19665

echo prints each argument separated by a space then adds a newline at the end.

printf '%s\n' prints each argument with a new line as it repeats the format string as long as there are elements to consume.

#!/usr/bin/env bash

# Populates array
arr=(foo bar baz cuux)

printf 'Output from echo:\n'
echo "${arr[@]}"

printf '\nOutput from printf:\n'
printf '%s\n' "${arr[@]}"

results:

Output from echo:
foo bar baz cuux

Output from printf:
foo
bar
baz
cuux

If you want the output of printf be like the output of echo, expand the array as a single argument:

#!/usr/bin/env/bash

# Populates array
arr=(foo bar baz cuux)

# Print all entries as one argument (similar to echo)
printf '%s\n' "${arr[*]}"

Upvotes: 3

Related Questions