Write a small script to count ERROR lines in a log file.
⚡
Quick Answer
Read the file line by line and count lines containing ERROR. In Python: open the file, iterate, increment a counter when ERROR is in the line, and print the total. On the shell, grep -c ERROR app.log does it in one command.
Detailed Answer
Line-by-line iteration keeps memory flat even for huge logs (do not read the whole file into memory). The shell one-liner grep -c ERROR app.log is the pragmatic answer; the Python version is useful when you need more logic (parse fields, group by hour). For structured JSON logs, jq is the better tool.
Code Example
count = 0
with open("app.log") as f:
for line in f:
if "ERROR" in line:
count += 1
print("Total ERROR messages:", count)
# shell equivalent: grep -c ERROR app.log💡
Interview Tip
Give the grep -c one-liner as the pragmatic answer and note line-by-line iteration keeps memory flat on huge logs.
linuxpythonlogsscripting