0

I am a new bash learner. I want to know, how to take a list of string from standard input? After taking all of the strings, I want to print them space separated.

Say the input is like the following:

Namibia
Nauru
Nepal
Netherlands
NewZealand
Nicaragua
Niger
Nigeria
NorthKorea
Norway

The output should be like:

Namibia Nauru Nepal Netherlands NewZealand Nicaragua Niger Nigeria NorthKorea Norway

I just can read a variable in bash and then can print it like the following:

read a
echo "$a"

Please, note that :

This question does not answer my question. it is mainly on traversing a declared array. but my case is handling the input and appending the array in runtime as well as detecting the EOF

Community
  • 1
  • 1
Enamul Hassan
  • 5,266
  • 23
  • 39
  • 56
  • cat /tmp/file_with_countires | awk '{printf("%s ", $0)}' – klerk Jun 30 '15 at 08:10
  • It is not from file, it is from standard input. @klerk – Enamul Hassan Jun 30 '15 at 08:12
  • The [question you referred](http://stackoverflow.com/questions/8880603/loop-through-array-of-strings-in-bash-script) is mainly on traversing a declared array. but my case is handling the input and appending the array in runtime as well as detecting the ``EOF`` @Identity1 – Enamul Hassan Jun 30 '15 at 08:14

2 Answers2

5

You can use read in a loop with a bash array:

countries=()
while read -r country; do
    countries+=( "$country" )
done
echo "${countries[@]}"

If used interactively, Ctrl-d terminates the loop, otherwise it will terminate once read fails (e.g. at EOF). Each country is printed on the same line.

Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
1

Assuming your list is a file (you can always save to a file):

my_array=( $(<filename) )
echo ${my_array[@]}

From standard input:

while :
do
read -p "Enter something: " country
my_array+="country"
done