Search code examples
bashshellfile-read

Read a file and put specific values to an array


I am a newbie to bash scripting. I have a file containing some values. I want to put all the values of a specific key into an array in bash. The file looks like this.

file.properties
name=val1
name=val2
name=val3
age=val4

I want to read this file and get all the name values into one array in bash.


Solution

  • You can try the following:

    #!/bin/bash
    while read -r line; do
        arr=("${arr[@]}" "$line")
    done < <(grep name= file.properties | sed "s/name=//")
    echo "${arr[@]}"