grep regular expressions: Which pattern anchors a match to the end of a line so that only lines ending with the text “pat” are selected?

Difficulty: Easy

Correct Answer: pat$

Explanation:


Introduction / Context:
grep uses basic regular expressions to match text in files or streams. Anchors are special metacharacters that constrain where a pattern must appear in a line. The dollar sign $ anchors the pattern to the line end, and the caret ^ anchors to the line start.


Given Data / Assumptions:

  • You want lines that end with the literal substring “pat”.
  • You are using grep (basic regex) without extended flags.
  • No special escaping is needed for letters; anchors retain their special meaning.


Concept / Approach:
To match “pat” only at the end, write pat$ so that “pat” must immediately precede the end of the line. Using ^pat would instead require “pat” at the beginning. Placing anchors incorrectly or in the wrong order will change the match or render it meaningless.


Step-by-Step Solution:

Use: grep 'pat$' file.txtThis returns lines whose final characters read “pat”.Test with echo -e 'pat\ncompat\npattern' | grep 'pat$' → matches “pat” and “compat”.If you need an exact whole-line match, use ^pat$ instead.


Verification / Alternative check:
Experiment with ^pat to see it matches only at the start. Combine with character classes or quantifiers as needed, keeping the $ at the end to enforce line-ending.


Why Other Options Are Wrong:
^pat: start-of-line anchor. $pat / pat^: misordered anchors; not meaningful for the intended end-of-line constraint. None of the above: incorrect because pat$ is correct.


Common Pitfalls:
Forgetting that grep patterns are regex, not globbing; neglecting to quote the pattern in the shell to avoid unintended expansions; confusing ^ and $ with shell anchors.


Final Answer:
pat$

More Questions from Unix

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion