Search code examples
linuxsedgrepcut

How to grep and modify the environment variable from a file in linux?


# input file.yaml
conda_name: "test"
user_name: "foo"

How do I can the get user_name variable and export to local environment variable (without installing extra packages)? I do not know how to export the variable

# where I am stuck
 grep 'user_name:' file.yaml | sed 's/:/=/g'
# export the variable

Please feel free to use the approach that you think is the best. Thank you!


Solution

  • You can do this in a simple bash loop:

    while IFS=': ' read -r k v; do
       [[ $k = "user_name" ]] && declare -x $k="${v//\"/}"
    done < file
    
    echo "user_name"
    
    foo
    

    declare -x $k="${v//\"/}" exports a variable named $k which is user_name. ${v//\"/} strips double quotes present in your input file around foo.