BASH reading txt file and storing in array

IFS=$'\n' a=($(cat phonebook.txt))
for i in $(seq ${#a[*]}); do
    [[ ${a[$i-1]} = $name ]] && echo "${a[$i]}"
done

In Bash 4 IFS=$'\n' a=($(cat phonebook.txt)) can be replaced with mapfile -t a < phonebook.txt.

grep -A1 prints one line after the match. -x disables regex like -F but it only matches complete lines.

grep -x "$name" -A1 phonebook.txt | tail -n1

index=0
while read line; do
  myArray[index]="$line"
done < inputfile

Newer versions of bash support associative arrays. That would make it easier:

declare -A myArray
while read name; do
  read number
  myArray[name]="$number"
done < inputfile

echo ${myArray[name]}

In a question titled "BASH reading txt file and storing in array" I feel readarray deserves a mention. An example of this method I use to read test files into an array would be:

readarray -t arrayIPblacklist < /etc/postfix/IP-black-list.txt

The foregoing loads a file of IP addresses- separated by newlines- into an array called "arrayIPblacklist". Would work on your phonebook file. readarray was introduced in bash 4, so this method won't work on older hosts running earlier bash versions.

The -t option strips the newline delimiters from each element, as most of the time you don't want them included.

$ seq 3 | bash -c 'readarray a; printf "<%q>\n" "${a[@]}"'
<$'1\n'>
<$'2\n'>
<$'3\n'>
$ seq 3 | bash -c 'readarray -t a; printf "<%q>\n" "${a[@]}"'
<1>
<2>
<3>

Tags:

Bash

Files

Array