0

In Unix, I need an input validation which use grep:

echo $INPUT| grep -E -q '^foo1foo2foo3' || echo "no"

What I really need is if input doesn't match at least one of these values: foo1 foo2 or foo3, exit the program.

Source: syntax is taken from Validating parameters to a Bash script

3
  • Well the regex should probably be ^foo[123]$. Commented Jun 2, 2016 at 19:45
  • Be careful to use ^ and $ to anchor your matches if you want the entire value to match. Otherwise you could pass values like "foo14" and "aaafoo3zzz". Commented Jun 2, 2016 at 19:52
  • I was just copying from the source I found, I just need to match those words. Commented Jun 2, 2016 at 21:29

3 Answers 3

4

You need to use alternation:

echo "$INPUT" | grep -Eq 'foo1|foo2|foo3' || echo "no"
Sign up to request clarification or add additional context in comments.

4 Comments

You missed ^, I guess the OP needs a match on the beginning of the line.
Yes because OP wrote if input doesn't match, question didn't say if these values must be at the start of each line.
Thanks, this works perfect, but the other answer is shorter. I was just copying the code from the other source, hence the "echo"
If you're doing this against a file then grep -Eq 'foo[1-3]' file would be shortest
2

Do you really need grep? If you're scripting in bash:

[[ $INPUT == @(foo1|foo2|foo3) ]] || echo "no"

or

[[ $INPUT == foo[123] ]] || echo "no"

If you want "$INPUT contains one of those patterns

[[ $INPUT == *@(foo1|foo2|foo3)* ]] || echo "no"

1 Comment

Thank you, works great. I want to match exact so I'll use this [[ $INPUT == foo[123] ]] || echo "no"
2

Does this solve your problem:

echo $INPUT | grep -E 'foo1|foo2|foo3' || echo "no"

?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.