Kevin Amiranoff
Kevin Amiranoff

Reputation: 14468

How to get one value from a file and ignore commented lines?

I am trying to get the value of URL from a .env file but ignore lines that start with #

my .env

URL=staging
#URL=prod
OTHER_VAR=test

I am trying to save the value of URL inside of a variable using grep

Here is what I have:

MY_VAR=$(grep URL ./.env | cut -d '=' -f 2-)

I have tried to use:

MY_VAR=$(grep -v '^#' ./.env | cut -d '=' -f 2-)

but don't know how to specify which variable I want to get the value from

Upvotes: 3

Views: 201

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626758

You may match those lines that begin with URL= and get the value after this text only using a single sed command:

MY_VAR="$(sed -n 's/^URL=//p' ./.env)";

Here, -n suppresses the default line output, s/^URL=// removes URL= at the start of the matched line (^ is the start of string anchor) and p prints the result, i.e. what is after URL=.

If there can be whitespace before URL=, you may add [[:space:]]* after ^:

MY_VAR="$(sed -n 's/^[[:space:]]*URL=//p' ./.env)";

@Sundeep's PCRE-based grep command works similarly. grep -oP '^URL=\K.+' ./.env or grep -oP '^\s*URL=\K.+' ./.env will yield the same results as above sed commands (in a PCRE pattern, you may match whitespaces with \s shorthand character class).

Upvotes: 4

Related Questions