Nahshon paz Nahshon paz - 10 months ago 55
Bash Question

Matching a pattern with sed and getting an integer out at the same time

I have an xml file with these lines (among others):

#Enter your required DEV environment after the ENV= in the next line:

I need to:

  1. Verify that the text after
    is of the pattern

  2. extract the number (in this case, 6) from the line
    to some environment variable

I know a bit of awk and grep, and can use those to get the number, but I'm thinking of Sed, which I'm told matches patterns nicer than awk and takes less time. Also, I'm concerned about long long lines of greps matching the beginning of the line for that particular Env= .

How would I go about doing it with Sed? would I get away with a shorter line?

I'm a sed newbie, read a bunch of tutorials and examples and got my fingers twisted trying to do both things at the same time...

Answer Source

I suggest with GNU sed:

var=$(sed -nE 's/^Env=DEV([0-9]{1,2})$/\1/p' file)
echo "$var"