Challenge your command line skills with this quiz on Linux text processing using awk, sed, and grep. Assess your knowledge of syntax, common use cases, and practical text manipulation techniques in Unix-like environments.
Which grep command would correctly display all lines in file.txt that contain the word 'error' regardless of letter case?
Explanation: The '-i' option in grep makes the search case-insensitive, ensuring words like 'Error', 'ERROR', and 'error' are all matched. The basic 'grep error file.txt' is case-sensitive and would miss variants with different letter cases. The '-c' option counts matching lines rather than displaying them, making it unsuitable for viewing lines directly. The fourth option combines '-n' and '-c' incorrectly; '-c' overrides the display to just the count. Only the first command matches the requirement.
How does the command awk '{print $3}' data.log behave when used on a space-separated file?
Explanation: The syntax '{print $3}' tells awk to print the third field (column) on each line by default, when fields are space-separated. It doesn't affect the number of lines printed, so option two is incorrect. awk does not delete fields using this syntax, making option three wrong. Lastly, it does not display a column count, so the fourth option is unsuitable. The first option correctly describes the behavior.
Given a file called sample.txt, which sed command replaces every occurrence of 'foo' with 'bar' in each line?
Explanation: The correct sed substitution syntax is 's/pattern/replacement/g', where 'g' allows for global replacement on each line. The second option uses 'r', which is not valid in this context. The third uses 'd', which is for deletion, not substitution. The fourth option omits the 'g' flag, so it would only replace the first occurrence per line, not all. Only the first option performs the intended global replacement.
What does the command grep '^start' notes.txt do when run on a file named notes.txt?
Explanation: The caret (^) in regular expressions matches the start of a line, so grep '^start' looks for lines where 'start' is at the beginning. It does not highlight occurrences within lines, so the second option is wrong. It is not used for deleting lines, making three incorrect. The last option relates to lines ending with 'start', which would require a dollar sign ($) at the end. The first option is correct.
When processing a file with awk, what does the variable NR represent?
Explanation: NR in awk stands for 'Number of Records' and represents the line number currently being processed. It does not hold any field value, so the second option is incorrect. The third option confuses NR with NF, which counts fields. The fourth option is inaccurate, as NR cannot access previous lines. Thus, the first option correctly captures NR's purpose.