Explore critical features and use cases of 'grep' for text searching and filtering in command-line environments. This quiz aims to deepen understanding of pattern matching, regular expressions, option flags, and practical grep scenarios frequently faced by CLI users.
Which command will display only the lines containing the word 'config' (case-sensitive) from a file named settings.txt?
Explanation: The correct command is 'grep config settings.txt' because it searches for exact matches of 'config' in a case-sensitive manner. The '-i' option ignores case differences, which isn't required for case-sensitive searches. The '-v' flag inverses the match, showing lines that do NOT contain 'config.' Although 'grep .*config.* settings.txt' appears to use regular expressions, 'grep config settings.txt' already finds all occurrences, making the explicit use of '.*' unnecessary.
How can you display the line numbers of each matching line containing 'error' in a file called app.log?
Explanation: The '-n' option in 'grep -n error app.log' displays the line numbers alongside each matching line. The '-l' flag lists only the filenames with matches and does not print line numbers. '--lines' and '-num' are not valid grep options, making these distractors incorrect.
If you want to filter out all lines that include the word 'debug' from output.txt, which grep command should you use?
Explanation: The '-v' flag in grep excludes lines containing the specified pattern, so 'grep -v debug output.txt' filters out those lines. The '-r' option is for recursive searches in directories, not for excluding matches. '--exclude' omits files from being searched, but not lines. '-e' allows specifying a pattern, but does not exclude lines.
Which command finds lines starting with the word 'Warning' in monitor.log, using regular expressions?
Explanation: The '^' symbol in regular expressions marks the start of a line, so 'grep '^Warning' monitor.log' matches lines beginning with 'Warning'. Using 'Warning$' matches lines ending with 'Warning', not starting with it. The '-w' option finds whole-word matches anywhere in the line, not just at the start. '--begin' is not a recognized option in grep.
When searching for the pattern 'token' across all text files in a directory and its subdirectories, which command is correct?
Explanation: The '-r' flag in 'grep -r token .' enables recursive search across all files and subdirectories from the current directory. 'grep -r token *.txt' may not search in subdirectories as expected, since the shell expands '*.txt' before grep starts. The '-a' option treats files as text, but does not control recursion. '--tree' is not a valid grep flag.