简体   繁体   中英

How to print a bash array on the same line

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?

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

readarray retains the trailing newline in each array element. To strip them, use the -t option.

readarray -t myArray < "$1"

One way :

printf '%s\n' "${myArray[@]}" | paste -sd ' '

or simply :

printf '%s ' "${myArray[*]}"

In case you have the array elements coming from input, this is how you can

  • create an array
  • add elements to it
  • then print the array in a single line

The script:

#!/usr/bin/env bash

declare -a array
var=0
while read line
do
  array[var]=$line
  var=$((var+1))
done

# At this point, the user would enter text. EOF by itself ends entry.

echo ${array[@]}

我最喜欢的技巧是

echo $(echo "${myArray[@]}")

@sorontar's solution posted in a comment was handy:

printf '%s ' "${myArray[@]}"

but in some places the leading space was unacceptable so I implemented this

local str
printf -v str ' %s' "${myArray[@]}"  # save to variable str without printing
printf '%s' "${str:1}"  # to remove the leading space 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM