user2847598
user2847598

Reputation: 1299

Regex match using one expression

Is there a way to match only the first two lines using one regular expression (not using the "or" matching like: ^cmd$|^cmd[[:space:]]+)?

cmd
cmd -option
cmdanother
cmdanother -option

The word cmdanother can be anything starting with cmd.

P.S., thanks all for the answer. It works in the above case. However, if there is a line like:

cmd-anything

It is also selected (seems - is a word boundry). Is there a fix to this?

Upvotes: 0

Views: 67

Answers (3)

anubhava
anubhava

Reputation: 785128

You can ditch regex and use awk like this:

awk '$1 == "cmd"' file
cmd
cmd -option

Upvotes: 1

Kent
Kent

Reputation: 195049

if the input is exactly like what you have given, \b could work.

^cmd\b

just checking the beginning and ignore the ending should work.

However, the \b doesn't only match space, :,.?... would be matched as well. E.g lines cmd:foo, cmd.foo ... would be matched.

If they are not concerned, just take the \b one, otherwise, you do need | (or) like:

^cmd( .*|$) 

BRE: ^cmd\( .*\|$\)

Upvotes: 3

Avinash Raj
Avinash Raj

Reputation: 174706

Use word boundary \b,

^cmd\b.*$

DEMO

Upvotes: 0

Related Questions