Santiago San Martin
Santiago San Martin

Reputation: 94

How to make a regex match with grep in shell script?

I am trying to create a shell script that matches a string with a predefined regex. I have the following code:

#!/bin/sh
name="Name of string to match. #123"

(echo "$name" | grep -Eq  ^[#]\d+$) && echo "matched" || echo "did not 
match"

I am always getting a "did not match" message, even though I think the string in the example should match the regex. Can anyone realize what I am doing wrong? Is the regex wrong or is it the call to grep?

Upvotes: 2

Views: 1979

Answers (1)

Bohemian
Bohemian

Reputation: 424983

Wrap the regex in quotes:

(echo "$name" | grep -Eq '^[#]\d+$') && echo "matched" || echo "did not match"

If you expect the sample input to match, remove the start-of-input anchor ^, ie use '[#]\d+$' as your regex (which would match anything ending in # then digits).

Upvotes: 3

Related Questions