Takuhii
Takuhii

Reputation: 925

Convert eGrep to Grep

I have a query using eGrep in Bash on MacOS, and wondered how to convert it to grep query instead, as I understand eGrep is deprecated now, or is being replaced in favour of grep?

I need to convert this;

egrep "^\s+2\.\d+\.\d+$" <(rbenv install -l) | tail -1

Basically it is looking in the RBENV install list for the latest 2.x version so it can install it later on, this portion of code harvests the version number I need and stores it in a VAR for later use ;) Any help would be greatly appreciated

Upvotes: 2

Views: 479

Answers (3)

Takuhii
Takuhii

Reputation: 925

OK, so I figured it out the final query is this

latest_2x_ruby=$(grep -E "^2\.\d+\.\d+$" <(rbenv install -l) | tail -1)

This will retrieve all version numbers starting with 2 and pick the last one from the list. this way I Can just change the number at the start to retrieve the latest version of a specific major version.

However, if I want to run this from a BASH script I had to do it this way;

latest_2x_ruby="$( rbenv install -l | grep -E '^2\.\d+\.\d+$' | tail -1 )"

Upvotes: 0

Tom Fenech
Tom Fenech

Reputation: 74595

As others have mentioned, egrep is an obsolescent version equivalent to grep -E.

The reason that your original command doesn't work on a non-GNU version of grep is because you are using unsupported syntax like \s and \d. This is a separate feature to Extended Regular Expression support (which is what you get with -E).

Try changing \s and \d for their equivalent longhand syntax:

grep -E '^[[:space:]]+2\.[[:digit:]]+\.[[:digit:]]+$' <(rbenv install -l) | tail -1

As an aside, I would always recommend using single quotes around any string literal, to avoid characters such as $ and \ from potentially being interpreted by the shell.

For maximum compatibility you may also want to consider using a pipe rather than a process substitution, and only using Basic Regular Expression syntax (i.e. replacing + with \{1,\}):

version=$(rbenv install -l | 
  grep '^[[:space:]]\{1,\}2\.[[:digit:]]\{1,\}\.[[:digit:]]\{1,\}$' |
  tail -1)

Upvotes: 3

tomgalpin
tomgalpin

Reputation: 2093

See: https://www.gnu.org/software/grep/manual/grep.html

egrep is a synonym for grep -E

fgrep is a synonym for grep -F

In your case egrep "^\s+2\.\d+\.\d+$" <(rbenv install -l) | tail -1

simply becomes

grep -E "^\s+2\.\d+\.\d+$" <(rbenv install -l) | tail -1

Upvotes: 3

Related Questions