0

I have a bash script and I want to create an array from the lines of a txt file without the end of line character.

The file contains countries like this (may contain spaces too).

Afghanistan
Albania
Antigua and Barbuda
Argentina
Armenia
Australia
Central African Republic
.
.
.

My goal is to have an array named COUNTRIES that holds every line from the text file above and to echo a string that has a couple of variables and the country in the middle without the end of line.

For example, for : NAME = "ALEX", AGE = 21 and COUNTRY=${COUNTRIES[2]}, I want the command

echo $NAME $COUNTRY $AGE to output ALEX Antigua and Barbuda 21 in a single line.

I tried using mapfile COUNTRIES < ${COUNTRIES_FILE}, but the above echo outputs 21ALEX Antigua and Barbuda for some reason.

Using mapfile -t COUNTRIES < ${COUNTRIES_FILE} outputs the same string.

I then tried COUNTRIES+=($(cat ${COUNTRIES_FILE})), but that did not work either.

Any ideas?

  • Does [this](https://stackoverflow.com/a/6022441/11261546) answer your question? – Ivan Mar 04 '21 at 21:03
  • See https://ideone.com/SRjAgQ showing your code (with `mapfile -t`) working fine as-is -- no extra newlines added. (And note that variable names should be _lowercase_ to avoid conflicting with [reserved names used by the shell itself](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html); see the line from that specification: "*The name space of environment variable names containing lowercase letters is reserved for applications*"). – Charles Duffy Mar 04 '21 at 21:05
  • 1
    are you sure you are setting variables like that? `NAME = "ALEX"`? there should not be any whitespaces around `=` – αғsнιη Mar 04 '21 at 21:05
  • 2
    Your file has CRLF line breaks. Use `dos2unix` to fix it. – Barmar Mar 04 '21 at 21:15
  • 1
    *facepalm*, I confused which sample was actual vs expected output. @Barmar is completely right above, and that makes this a duplicate of [Are shell scripts sensitive to encoding and line endings?](https://stackoverflow.com/questions/39527571/are-shell-scripts-sensitive-to-encoding-and-line-endings) – Charles Duffy Mar 04 '21 at 21:18

0 Answers0