David Turner
David Turner

Reputation: 59

grep pattern match with multiple variables

I have been searching around for over an hour and I am not quite finding what I am looking for. I am trying to perform a grep match to make sure the syntax in a command is correct before proceeding.

Contents of file:

deploy type:apptype1 artifact:coolio version:1.1.1 in dev

What I am looking for is to allow multiple types, artifact, version and allow for only dev or qa. Any other text added or missing should fail.

What I have tried so far is:

grep -ie "deploy type:apptype1\|apptype2\|apptype3 artifact:.*version:.*in dev\|qa file

The problem is if I add additional text or even change "in" to "on" it still matches. I suspect it is only matching the first part and not the entire line like I am wanting?

Upvotes: 1

Views: 533

Answers (3)

comdotlinux
comdotlinux

Reputation: 153

This works for me :

echo "deploy type:apptype2 artifact:coolio version:1.1.1 in dev" | grep -i -E "deploy type:(apptype1|apptype2|apptype3) artifact:.*version:.*in (dev|qa)"

Note the > color on the next line indicating previous command returned 0 (Green) or else non zero (Red)

vaidatingByExitCode

Upvotes: 1

jared_mamrot
jared_mamrot

Reputation: 26495

Based on your example, here is a solution for BSD/GNU grep:

grep -ie "deploy type:apptype[123] artifact:[[:alnum:]].* version:[[:alnum:]].* in [(dev\|qa)]" file

Edit

@timur-shtatland's answer is better - my answer will not exclude "dev_test" or "qa_temp"

Upvotes: 1

Timur Shtatland
Timur Shtatland

Reputation: 12347

Use GNU grep:

grep -P '^deploy type:(apptype1|apptype2|apptype3) artifact:.*version:.*in (dev|qa)$' in_file

Example:

cat > in_file <<EOF
deploy type:apptype1 artifact:coolio version:1.1.1 in dev
deploy type:apptype2 artifact:coolio version:1.1.1 in qa
deploy type:apptype1 artifact:coolio version:1.1.1 on dev
EOF

grep -P '^deploy type:(apptype1|apptype2|apptype3) artifact:.*version:.*in (dev|qa)$' in_file

Output:

deploy type:apptype1 artifact:coolio version:1.1.1 in dev
deploy type:apptype2 artifact:coolio version:1.1.1 in qa

Here, GNU grep uses option:
-P : Use Perl regexes.

^ : Beginning of the line.
$ : End of the line.

SEE ALSO:
perlre - Perl regular expressions

Upvotes: 2

Related Questions