Select lines from ids.txt that are exactly api- followed by two digits or web- followed by two digits.
Partial matches must not be accepted.
api-07
web-12
xapi-07
api-7
db-12
api-071Which command is correct?
grep -E enables extended regular expressions. Anchors require the complete line to match, and {2} requires exactly two digits.
Detailed explanation
grep '(api|web)-[[:digit:]]{2}' ids.txtIncorrect. Basic regular expressions do not interpret these ERE operators as intended.
Incorrect. Basic regular expressions do not interpret these ERE operators as intended.
grep -E '(api|web)-[[:digit:]]{2}' ids.txtIncorrect. Without anchors it also matches a substring of a longer line.
Incorrect. Without anchors it also matches a substring of a longer line.
grep -E '^(api|web)-[[:digit:]]{2}$' ids.txtCorrect. -E, anchors, and {2} express the exact whole-line pattern.
Correct. -E, anchors, and {2} express the exact whole-line pattern.
grep -F '^(api|web)-[[:digit:]]{2}$' ids.txtIncorrect. -F treats the pattern as literal text.
Incorrect. -F treats the pattern as literal text.
Try it yourself
An example you can run in a temporary verification environment.
printf '%s
' api-07 web-12 xapi-07 api-7 db-12 api-071 > ids.txt
grep -E '^(api|web)-[[:digit:]]{2}$' ids.txtExpected result
api-07
web-12Key points
- ERE with grep -E
- Line anchors ^ and $
- Exact repetition with {2}
Notes
- Environment: GNU grep 3.x / LC_ALL=C
- Command output formatting can vary slightly by distribution or tool version.
- Run the example in a temporary directory or process when possible.
Foundation review
Read the scope first
Check whether the command acts on the current shell, a new process, an existing process, or a file.
Verify the observable result
Use the supplied command and compare the output with the expected result.