With grep, which anchor matches the literal pattern 'pat' only at the beginning of a line in a text file?

Difficulty: Easy

Correct Answer: ^pat

Explanation:


Introduction / Context:
Anchors in regular expressions control where a pattern can match within each line. Mastering these anchors is crucial for precise searches, log filtering, and data extraction with grep and related tools like sed and awk.


Given Data / Assumptions:

  • We are using basic or extended regular expressions compatible with grep.
  • We need to match the literal string 'pat' only when it appears at the start of a line.
  • Multiline context is per-line (standard grep behavior).


Concept / Approach:

The caret anchor ^ matches the beginning of a line. Therefore, ^pat matches lines that start with 'pat'. By contrast, the dollar anchor $ matches the end of a line, so pat$ would anchor at the end, not the beginning.


Step-by-Step Solution:

Select beginning-of-line anchor: ^Combine with pattern: ^patCommand usage: grep '^pat' file.txtOptionally ignore case: grep -i '^pat' file.txt


Verification / Alternative check:

Create a sample file with lines that begin with and do not begin with 'pat' and test the command. Only those starting with the sequence will be matched.


Why Other Options Are Wrong:

  • $pat: invalid anchor usage; $ is an end-of-line anchor, not a prefix.
  • pat$: anchors 'pat' at the end of the line.
  • pat^: invalid for start anchoring; the caret must precede the pattern.
  • None of the above: incorrect because ^pat is correct.


Common Pitfalls:

  • Forgetting to quote patterns that include special characters to avoid shell interpretation.
  • Confusing ^ and $ roles.


Final Answer:

^pat.

More Questions from Unix

Discussion & Comments

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