I am reading in filetype data into a bash array and need to print its contents out on the same line with spaces.
#!/bin/bash
filename=$1
declare -a myArray
readarray myArray < $1
echo "${myArray[@]}"
I try this and even with the echo -n flag it still prints on newlines, what am I missing, would printf work better?
To print the array elements on a separate line, we can use the printf command with the %s format specifier and newline character \n in Bash. @$ expands the each element in the array as a separate argument. %s is a format specifier for a string that adds a placeholder to the array element.
To print each word on a new line, we need to use the keys “%s'\n”. '%s' is to read the string till the end. At the same time, '\n' moves the words to the next line. To display the content of the array, we will not use the “#” sign.
Printing Newline in Bash The most common way is to use the echo command. However, the printf command also works fine. Using the backslash character for newline “\n” is the conventional way.
Simple way to print in one line
echo "${myArray[*]}"
example:
myArray=(
one
two
three
four
[5]=five
)
echo "${myArray[*]}"
#Result
one two three four five
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