Search code examples
bashshellgrepshcut

Shell file doesn't extract value properly [grep/cut] from file [bash]


I have a test.txt file which contains key value pair just like any other property file.

test.txt

Name="ABC"
Age="24"
Place="xyz"

i want to extract the value of different key's value into corresponding variables. For that i have written the following shell script

master.sh

file=test.txt
while read line; do
  value1=`grep -i 'Name' $file|cut -f2 -d'=' $file`
  value2=`grep -i 'Age' $file|cut -f2 -d'=' $file`
done <$file 

but when i execute it; it doesnt run properly, giving me the entire line extracted by the grep part of the command as output. Can someone please point me to the error ?


Solution

  • If I understood your question correctly, the following Bash script should do the trick:

    #!/bin/bash
    
    IFS="="
    while read k v ; do
        test -z "$k" && continue # skip empty lines
        declare $k=$v
    done <test.txt
    
    echo $Name
    echo $Age
    echo $Place
    

    Why is that working? Most information can be retrieved from bash's man page:

    • IFS is the "Internal Field Separator" which is used by bash's 'read' command to separate fields in each line. By default, IFS separates along spaces, but it is redefined to separate along the equal sign. It is a bash-only solution similar to the 'cut' command, where you define the equal sign as delimiter ('-d =').
    • The 'read' builtin reads two fields from a line. As only two variables are provided (k and v), the first field ends up in k, all remaining fields (i.e. after the equal sign) end up in v.
    • As the comment states, empty lines are skipped, i.e. those where the k variable is emtpy (test -z).
    • 'eval' is a bash builtin as well, which executes the arguments (but only after evaluating $k=$v), i.e. the eval statement becomes equivalent to Name="ABC" etc.
    • '<test.txt' after 'done' tells bash to read test.txt and to feed it line by line into the 'read' builtin further up.
    • The three 'echo' statements are simply to show that this solution did work.