Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Extract variable value from file
This should extract the value of a variable from a text file.
It works fine with bash/sh and makefile variables.
Had to use 2 sed()s to deal with name='value' cases.
Fixes are welcome.
$ VAR_NAME=PREFIX
$ sed --version
GNU sed version 4.1.5
$ cat filename.conf | \
sed -ne \
"s%^[[:space:]]*\(export[[:space:]]\+\)\?$VAR_NAME[[:space:]]*[:?+]\?=[[:space:]]*['\"]\([^'\"]\+\)['\"].*%\2%p" \
|| \
sed -ne \
"s%^[[:space:]]*\(export[[:space:]]\+\)\?$VAR_NAME[[:space:]]*[:?+]\?=[[:space:]]*\([^'\"#[:space:]]\+\).*%\2%p"
=== Example file ===
PREFIX=a-1
PREFIX = a-2
PREFIX =a-3
PREFIX= a-4
PREFIX='a 5'
PREFIX = 'a seis'
PREFIX ='a sete'
PREFIX= 'a oito'
PREFIX="a nove"
PREFIX = "a dez"
PREFIX ="a onze"
PREFIX= "a doze"
PREFIX=b-1 # comentario
PREFIX = b-2 # comentario
PREFIX =b-3 # comentario
PREFIX= b-4 # comentario
PREFIX='b 5' # comentario
PREFIX = 'b seis' # comentario
PREFIX ='b sete' # comentario
PREFIX= 'b oito' # comentario
PREFIX="b nove" # comentario
PREFIX = "b dez" # comentario
PREFIX ="b onze" # comentario
PREFIX= "b doze" # comentario
export PREFIX=c-1
export PREFIX = c-2
export PREFIX =c-3
export PREFIX= c-4
export PREFIX='c 5'
export PREFIX = 'c seis'
export PREFIX ='c sete'
export PREFIX= 'c oito'
export PREFIX="c nove"
export PREFIX = "c dez"
export PREFIX ="c onze"
export PREFIX= "c doze"
export PREFIX=d-1 # comentario
export PREFIX = d-2 # comentario
export PREFIX =d-3 # comentario
export PREFIX= d-4 # comentario
export PREFIX='d 5' # comentario
export PREFIX = 'd seis' # comentario
export PREFIX ='d sete' # comentario
export PREFIX= 'd oito' # comentario
export PREFIX="d nove" # comentario
export PREFIX = "d dez" # comentario
export PREFIX ="d onze" # comentario
export PREFIX= "d doze" # comentario
export PREFIX :='--d sete' # comentario
export PREFIX?= '--d oito' # comentario
export PREFIX+="--d nove" # comentario
export PREFIX := "--d dez" # comentario
export PREFIX ?="--d onze" # comentario
export PREFIX:= "--d doze" # comentario
=== End example file ===
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment