2

I have a file with data like this:

UserName
UserName
UserName

Each piece of data is separated by a new line.

I need that data to be converted to an array of strings and stored in a variable.

How do I achieve this with just bash or shell execution?

  • 1
    Can there be multiple strings per line (separated by space or even tab or comma)? If yes, should they be stored as one or as multiple values? – Freddy Aug 27 at 1:53
  • only one string per line, theyre each stored as a single value. each string is only seperated by a new line – David Aug 27 at 1:54
5

With mapfile:

$ mapfile -t array < yourfile

$ declare -p array # print array content
  declare -a array=([0]="UserName" [1]="UserName" [2]="UserName")
3
$ set -f             # disable globbing
$ arr=($(<file.csv))
$ set +f             # enable globbing
$ declare -p arr     # print array content
declare -a arr=([0]="UserName" [1]="UserName" [2]="UserName")
  • arr=(…) create array
  • $(<file.csv) read file file.csv (like $(cat file.csv))

Before the file is read, globbing should be disabled to prevent the expansion of user names with characters like * or ? or special patterns (pathname expansion).

The elements are split at newline, space or tab characters (assuming $IFS has not been modified) and trimmed.

2
i=0
while IFS= read -r line
do
  var[i++]="$line"
done < filename

Here var array variable stores all names. And can be accessed by

printf '%s\n' "${var[0]}"
printf '%s\n' "${var[1]}"
...
...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.