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
-
sudoaccess to install thewordspackage
-
Install the dictionary and search without anchors
The file
/usr/share/dict/wordscomes from thewordspackage, which is not installed by default.ssh student@servera sudo dnf install -y words ls -l /usr/share/dict/wordsSearch the dictionary for a short word and note how many unrelated results appear, such as
bobcatandduplicate.grep 'cat' /usr/share/dict/words -
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/wordsAdd
$instead, to require that the match run to the end of the line.grep 'cat$' /usr/share/dict/wordsWith both anchors the line must contain exactly this word and nothing else.
grep '^cat$' /usr/share/dict/words -
Use a start anchor to identify directories
The first character of each line of
ls -loutput is the file type. Without an anchor, searching fordmatches almost every line.ls -l /etc | grep 'd'Anchored to the beginning of the line, it returns only directories.
ls -l /etc | grep '^d' -
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$'