BASH reading txt file and storing in array

arraybashfiles

I'm writing my first BASH script , I have some experience with c and c# so I think the logic of the program is correct..it's just the syntax is so complicated because apparently there are billions of ways to write the same thing!

Anyway here is the script: it simply checks if the argument (string) is contained in a certain file . If so it stores each line of the file in an array and writes an item of the array in a file. I'm sure there must be easier ways to achieve that but I want to do some practice with bash loops

    #!/bin/bash

NOME=$1
c=0


#IF NAME IS FOUND IN THE PHONEBOOK THANK STORE EACH LINE OF THE FILE INTO ARRAY
#ONCE THE ARRAY IS DONE GET THE INDEX OF MATCHING NAME AND RETURN ARRAY[INDEX+1]

if grep  "$NOME" /root/phonebook.txt ; then
        echo "CREATING ARRAY"
        while read line
        do
                myArray[$c]=$line # store line
                c=$(expr $c + 1) # increase counter by 1
        done < /root/phonebook.txt

else
        echo "Name not found"
fi

c=0
for i in myArray;
        do
              if   myArray[$i]="$NOME" ;  then
                 echo ${myArray[i+1]} >> /root/numbertocall.txt
              fi

done

This code does returns the only the second item of myArray (myArray[2] or the second line of the file)..why?

Best Answer

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
Related Question