Home > Enterprise >  Extract string from text file with sed
Extract string from text file with sed

Time:12-28

I have a text file called .env like this:

SOME_VAR="value"
SOME_VAR_2="value2"
NODE_ENV="staging"
SOME_VAR_3="value3"

I need to extract the string in between " and " where the lines begin with NODE_ENV=

In other words, I need the string staging from that file. Then I need to use a command like.

Right now I have this:

git checkout $(cat .environment)

Where .environment is a file with a single value staging, so with that command I got:

git checkout $(cat .environment)

but now I need what I said before, to extract the value from a file with multiple lines in the mentioned format.

I tried with sed but I'm not sure how to use it:

sed -r '/NODE_ENV.*/I!d;s/.*:.(.*).}$/\1/' .env

but that's:

NODE_ENV="staging"

and what I need is to get:

staging

CodePudding user response:

Your regexp is looking for a : character, but there's no : in the file. You should be looking for ="..." and use the capture group to match what's between the ".

sed -n -r '/NODE_ENV/s/.*="(.*)"/\1/p' .env

Use the -n option to disable default printing, then append p to the command to print that matching line after the substitution.

CodePudding user response:

You can combine some simple commands:

echo .env | grep NODE_ENV | sed -E 's/.*"(.*)"/\1/'
  • Related