Exercise

Line Anchors Exercise

Task

In this hands-on exercise, anchor patterns to the start or end of a line, then use those positions to filter a directory listing.

Target host
servera
Privileges
sudo access to install the words package
  1. Install the dictionary and search without anchors

    The file /usr/share/dict/words comes from the words package, which is not installed by default.

    ssh student@servera
    sudo dnf install -y words
    ls -l /usr/share/dict/words

    Search the dictionary for a short word and note how many unrelated results appear, such as bobcat and duplicate.

    grep 'cat' /usr/share/dict/words
  2. Compare start, end, and exact-line anchors

    Add ^ to require that the match start at the beginning of the line.

    grep '^cat' /usr/share/dict/words

    Add $ instead, to require that the match run to the end of the line.

    grep 'cat$' /usr/share/dict/words

    With both anchors the line must contain exactly this word and nothing else.

    grep '^cat$' /usr/share/dict/words
  3. Use a start anchor to identify directories

    The first character of each line of ls -l output is the file type. Without an anchor, searching for d matches almost every line.

    ls -l /etc | grep 'd'

    Anchored to the beginning of the line, it returns only directories.

    ls -l /etc | grep '^d'
  4. Use an end anchor to identify configuration files

    A dot is a wildcard to grep, so escape it with a backslash to match a literal period.

    ls -l /etc | grep '\.conf$'