Ravindra BagaleCourses & study guides मराठी Track your progress

Chapter 4: Linux Advanced Commands

AWS Cloud

4.1 Searching text: grep

Friends, orders failed overnight on the Amul-style dairy server – now how will you find the error in a log with thousands of lines? The answer is grep. It is the most used search tool in Linux.

grep prints lines that match a pattern.

Option Meaning
-i Ignore case
-r / -R GNU recursive search. -r ordinarily skips discovered symlinks. -R follows them.
-n Show line numbers
-v Invert (lines that do NOT match)
-c Count matching lines
-l Only file names
-w Match whole word
-E Extended regex (alternation with a pipe symbol, +, ?)
-​A 3 / -​B 3 / -​C 3 Show 3 lines after / before / around
grep -i "error" /var/log/nginx/error.log
grep -rn "listen" /etc/nginx/
grep -nEv '^[[:space:]]*(#|$)' workshop.conf    # read a practice copy with leading whitespace handled
grep -c " 404 " /var/log/nginx/access.log          # candidate lines containing an interior 404 string; verify the status field separately
grep -E "Failed|Invalid" /var/log/auth.log         # Ubuntu SSH failures
sudo grep "Failed password" /var/log/secure         # AL2/CentOS (AL2023 uses journalctl)

Ravindra Bagale's Tip

Many students write grep error and miss the lines with Error or ERROR. The case varies in logs, so add -i: grep -i "error". And when searching a big folder use -rn – you get both the file name and the line number.

Lab

खालील local lab मध्ये workshop.conf मधील comment आणि blank lines बाजूला ठेवून उरलेला मजकूर वाचा. हा text search service च्या प्रत्यक्ष settings ची खात्री देत नाही. Access log साठी 404 हा मजकूर किती lines मध्ये आहे आणि status field मध्ये 404 असलेल्या records ची संख्या वेगळी तपासा.

Find the useful lines without losing the evidence

A workshop operator asks why a measurement import failed during the first morning run. The log contains successful uploads, warnings and several errors from different jobs. Opening the entire file is possible, but scrolling does not reliably identify which file and line describe the failed import. Start with one concrete question. “Which entries mention job ws-17, and do those entries show an error?” That question has a known target and leaves room to read the surrounding evidence before drawing a conclusion.

grep selects lines matching a pattern. For a normal search it reads a text stream or the files you name. It prints selected lines while leaving the input files alone. A line is a unit of text generally separated by a newline. The pattern can be a fixed string or a regular expression, a small language that describes possible text. Think about what you want selected before choosing the mode. If someone hands you a literal job ID, the ID is data. A pattern such as “the word ERROR at the start of a line” asks for a relationship and usually needs regular-expression syntax.

Give the command a specific file. A path identifies that file within your environment. A command run in an SSH shell uses the server's current working directory and files. A command run in your laptop terminal uses your local environment. Before searching an unfamiliar location, check where you are and whether the file is the one you meant to read. For this lesson the files are created in a local temporary directory. The examples do not require reading system authentication logs or running with administrator access.

A search result can be incomplete in several different ways. You may ask for the wrong file, use an inappropriate pattern, read data outside the useful time window, or encounter an access error. No output by itself does not tell you which of those happened. Keep the input path, command and exit status together. Once you have a line, interpret which component wrote it and what the message means. The presence of an error word is a way to locate evidence. It does not diagnose the incident on its own.

Use literal search for a value you already know

When you know the exact job identifier, ask grep to look for that string using -F. The option stands for fixed strings. Characters such as the period in a file name and the square brackets in a label are treated literally in the pattern. Without fixed-string mode, some of those characters have special meanings in a regular expression. Start with the simplest correct interpretation and add expression rules only when you need them.

Consider a file name readings.csv. An unescaped dot in a regex matches a character rather than requiring a literal period. It can also match text like readingsXcsv. If you need the exact name in a log line, grep -F 'readings.csv' events.log is a natural starting point. A match can still occur as part of a longer value. To enforce a complete structured field or line, add a known boundary under the actual input format. Literal matching protects the characters' meaning. It does not automatically identify where your application divides the data into fields.

Use shell quotes to pass the intended text to grep. With ordinary single quotes, most shell characters inside the quotes are passed as text, so the pattern reaches grep instead of being expanded first. Double quotes can still allow useful shell substitutions such as a variable's value. Put quotes around that value if it might contain spaces or wildcard characters. A pattern starting with a dash can be interpreted as an option unless it is passed as a pattern explicitly, for example with -e. The -- marker can tell a compatible command that later values are no longer options. Use those tools deliberately when looking up user-supplied text in a script.

Try this decision before typing the command. The requested job ID is ws-17, a second job is ws-170, and the line format has a separate job= field. A simple substring search for ws-17 will also find the longer value. You can use a literal that includes the known format boundaries where stable, such as a following space after the ID in a fixture that uses one space. For a log that records JSON objects, a format-aware reader can load the field and compare it for equality. First decide whether the task is to find promising lines or to compute a precise field-based result.

Keep the matched line long enough to read it. Options such as -n include the line number in the file. That is a location you can share with someone using the same unchanged input. A later rotation or edit can change numbering, so include the file and time range. An exact literal result with a meaningful location is a better support note than an unexplained screenshot of several red matches.

Choose a pattern that matches your actual question

A regular expression can describe text you do not know in advance. An anchor such as ^ matches the beginning of a line rather than matching a literal caret. The dollar anchor matches the end. A period can represent one character under ordinary regex matching rules. Square brackets describe a choice of characters or a class such as digits. In GNU grep's extended regular-expression mode, | joins alternatives and parentheses can group them. Keep the expression quoted in the shell so operators such as the pipe character reach grep as pattern text.

Work with a small sample on paper. One line is ERROR import failed. A second is INFO last ERROR cleared. A third is exactly ERROR. A plain literal search for ERROR selects all three because each contains the string. A regex beginning with ^ERROR selects the first and third. Using both anchors, ^ERROR$, selects the third. Ask which of those meanings fits the requested result. Many apparent search failures come from a correct command that was given the wrong question.

Now include case. A programmer wrote one message with Error and another with ERROR. The -i option performs case-insensitive matching according to the tool and locale. It is a good choice when searching for a human-facing symptom with inconsistent formatting. It is a poor default when the values differ meaningfully by case. A case-sensitive ID search should preserve its intended case. Describe whether you broadened the result to include variants. Check the pattern on three known lines before applying it to the full file.

Extended regex is useful for small controlled alternatives. If a practice log starts each severity with one of two precise labels, write a grouped expression anchored at the intended position. A pattern like ^(WARN|ERROR)[[:space:]] says that the first token is one of those exact labels followed by whitespace. Without parentheses, the pipe can separate branches differently. Test a deliberately nonmatching line that contains the word later in its message. That negative case tells you whether the anchor and grouping express the actual rule.

Grepping a line is different from understanding all of its fields. You can match predictable text effectively. If your real data follows JSON, CSV with quoted fields or another structured format, a parser can give a stronger equality or numeric result. Use grep to locate candidate lines or check a fixed marker. Use the format's rules for interpreting nested or escaped content. This distinction helps you choose between this lesson and the later text-processing lesson before building an unreliable counter.

Read line numbers, context and counts separately

The line containing an error often explains only the final symptom. Several lines before it can tell you which job opened the input, and later lines can report recovery. Context switches let you print neighbouring lines around a match. For example, after finding one known import failure, request a small amount of nearby context and read the job and timestamps. Neighbouring lines are included because of where they appear, even if they do not satisfy the pattern. Do not count every displayed line from context output as a match.

On a busy server, different jobs can interleave their log lines. A context line immediately following an error might concern another worker. Carry the matching job or request ID into the next search instead of assuming physical proximity in the file proves causation. If the log has structured timestamps and IDs, use them to narrow the time interval and correlate related entries. Read the specific job’s evidence around the reported time before grouping messages by the severity word alone.

The -c option counts selected lines. If one line contains ERROR twice and another line has it once, that option can report two lines. It does not count three appearances. If the assignment really asks for occurrences and your grep supports -o, printing matched portions and counting the output can answer a different question. Check how overlapping or repeated matches are handled by the tool. For a simple fixed marker in a one-line classroom fixture the difference is easy to observe. For a structured log, count the intended records instead.

Some options change what the command displays rather than the selection criterion. A filename-only search such as -l can help you decide which files to inspect next. After it finds relevant files, print a few matching lines with line numbers and filenames to inspect what those files actually contain. A quiet test with -q can be helpful in scripts, while a human checking errors or mixed input may need the diagnostics and actual selected lines. Choose output that lets the next person understand the result rather than making the terminal as short as possible.

Lab with one known log and several different search questions

You need a local shell with grep, basic file commands and a utility that can create a temporary directory. Use a GNU/Linux lab if you want the exact GNU grep behavior described here. On macOS or another system, the simple fixed-string and extended-regex cases should work with commonly shipped grep implementations, but check optional flags and diagnostics against that tool's manual. The lab uses fictional data, creates no services, and needs no administrator privileges.

Prepare the six lines

Save this copy in a new temporary folder. The shell variable records which folder belongs to this exercise. The redirection writes the fixture text into a new file in that folder. Its quoted delimiter keeps the body as literal text. On an unfamiliar shared machine, display the directory path and check it before continuing. The following searches read only these inputs.

GREP_LAB=$(mktemp -d)
printf '%s\n' "$GREP_LAB"
cat > "$GREP_LAB/events.log" <<'LOG'
INFO job=ws-17 opened readings.csv
WARN job=ws-170 prior ERROR cleared
ERROR job=ws-17 import failed; ERROR retry scheduled
INFO job=ws-18 opened readingsXcsv
Error job=ws-17 retry failed
INFO job=ws-17 training check passed
LOG

First read the important difference in the sample. There is a workshop job ws-17, a different job ws-170, and another job ws-18. The first and fourth lines have similar filenames with different characters between the first word and csv. The third line repeats ERROR. The fifth uses mixed case. The fixture puts several sources of mistakes together so you can solve them one at a time. The result is easier to check on six lines than on a busy application server.

Prove the search is as narrow as you intend

First ask grep to find the literal ID without a field boundary. Then repeat with the known whitespace after the full field value. The -n flag shows the line numbers. The first search can include line 2 for the longer ID. The second should select lines 1, 3, 5 and 6. This fixture always writes a space after the job field. A different log format could put that field last in a line or quote it differently. Use its actual format to choose another boundary if needed.

grep -Fn -- 'ws-17' "$GREP_LAB/events.log"
grep -Fn -- 'job=ws-17 ' "$GREP_LAB/events.log"

Now search for the exact filename and compare it to an expression with an unescaped dot. Predict where the broader expression matches. The fixed string should select only line 1. The ordinary expression should match line 1 and the altered look-alike on line 4 in this fixture. This is a practical reason to use fixed-string mode for machine identifiers. If you get an unexpected result, print the file with line numbers and compare the copied pattern to the actual text.

grep -Fn -- 'readings.csv' "$GREP_LAB/events.log"
grep -n -- 'readings.csv' "$GREP_LAB/events.log"

Separate severity from a word in the message

Search for records whose severity starts the line and uses either warning or error. The extended expression has an anchor, grouped alternatives and a required space-class character afterwards. The ignore-case option includes the mixed-case severity in this fixture. Expect lines 2, 3 and 5. Notice that line 2 has ERROR in the message, but its severity is WARN. A result for the word alone does not tell you the severity. For exact dashboard data in another log system, use the actual severity field or its configured output format.

grep -Ein -- '^(warn|error)[[:space:]]' "$GREP_LAB/events.log"
grep -n -C 1 -F -- 'import failed' "$GREP_LAB/events.log"

The second command requests one line before and after the matching failure. It should show lines 2, 3 and 4, with only the third line containing the requested phrase. Those neighbours are records for other jobs in this miniature example. Do not treat their timestamps or outcomes as part of the same import. To find the related lines for job 17, repeat the exact job-field search. This comparison is a concrete way to learn why context and correlation are separate choices.

Measure lines and occurrences as separate outcomes

Run two counts with the exact uppercase marker. The first uses the matching-line count. The second prints matched pieces and passes them to a line counter. This fixture has ERROR on line 2 and twice on line 3. The matching-line count should be two, while the count of printed matches should be three. Neither counts the mixed-case marker on line 5 without an explicitly broadened choice. Use the result you actually need, whether that is error records, literal appearances or distinct job failures.

grep -Fc -- 'ERROR' "$GREP_LAB/events.log"
grep -Fo -- 'ERROR' "$GREP_LAB/events.log" | wc -l

The line counter can report zero even if a command earlier in a pipeline could not read its input. In this exercise you know the fixture exists. In an automated report, confirm the input and check failures from the earlier commands too. Decide whether having no matched record is an expected condition, and avoid swallowing access errors. The next section shows how to record that distinction explicitly.

Keep the folder available for the next two exercises. After completing them, verify its path and remove only the named files you created. If you stop before those steps, remove only events.log and then the empty directory. A temporary directory path is useful only while it still points to the current lab folder. If a different process wrote other files into it, leave those files in place and inspect them before trying to remove the directory.

Read status as well as lines

An exit status is the small integer a program returns to its caller. GNU grep conventionally returns zero when it selected a line, one when it did not select a line, and two for an error. Other implementations may report an error with a different value above one. The shell stores the status of the most recent foreground command in the special $? value. Read it immediately after the command you want to diagnose. An unrelated echo or comparison can replace the status before you inspect it.

Use one known existing file and one absent path to observe the distinction. Search the existing file for a marker you know is present, then a marker you know is absent. Finally name a file the fixture did not create. Print the corresponding status after each. The expected results are zero for the matching line, one for no match and an error for the missing file. The missing-file check may also print a diagnostic on standard error. Silence in normal output is not enough information to decide whether the search succeeded.

grep -F -- 'readings.csv' "$GREP_LAB/events.log"
printf 'known-file match status: %s\n' "$?"
grep -F -- 'no-such-training-marker' "$GREP_LAB/events.log"
printf 'known-file no-match status: %s\n' "$?"
grep -F -- 'readings.csv' "$GREP_LAB/absent.log"
printf 'missing-file status: %s\n' "$?"

Some shells or training contexts enable error-exit behavior that stops a sequence after a nonzero status. Run these as separate interactive checks in the local practice shell. For an actual script, place the search in an explicit conditional if you need to handle both normal no-match and real errors. A scheduled review tool that treats a missing file as a clean run can make a serious reporting mistake. Store the status in a variable at the correct point.

Quiet mode deserves special attention. GNU grep can exit successfully when it finds a match under -q even if it also encountered an error. That is useful for some simple existential checks and risky when you must prove every input was readable and examined. A search used as an audit check should account for that difference. For a single known regular file, decide whether the quiet result or the complete selected output is the appropriate evidence. Check any error text that your report actually needs instead of redirecting it away by default.

Search several files without losing their names

When an application publishes separate logs for several workers, a match must identify which input file produced it. A filename can also contain a space. The shell phrases each command into arguments before grep starts. Quoting the full path keeps that path one argument. If you forget the quote, the command might try to read more than one file or report an error. Establish one known filename and successful direct search before applying a recursive search to a larger tree.

Use our temporary folder to prepare a tiny subdirectory and two new files. One is an authorised workshop log with a space in its name and two records. The other is a notes file that contains a matching ID but should be excluded from the later GNU example that chooses log filenames. The fixture deliberately carries one token across files. It lets you test whether file selection and line matching both work. If you stopped after the earlier lab, recreate its folder and events file first.

mkdir -- "$GREP_LAB/team"
printf '%s\n' 'INFO job=ws-17 review queued' 'INFO job=ws-18 review skipped' \
  > "$GREP_LAB/team/workshop notes.log"
printf '%s\n' 'INFO job=ws-17 sample text in a note' > "$GREP_LAB/team/example.txt"
grep -nH -F -- 'job=ws-17 ' "$GREP_LAB/team/workshop notes.log"

Expect the quoted file name, line number one and the review-queued message. The -H flag tells a compatible grep to print filenames even with one explicit file. This is useful when you combine results later. In a lab with several names, the output order can vary with implementation and filesystem traversal. Verify the file and line values rather than depending on search order to make a chronological claim. The log content and its timestamps are separately responsible for reporting time.

With GNU grep, run a scoped directory search. It should read the named directory recursively, apply the include pattern to eligible files, and print matching lines with file names and line numbers. The include glob is shell quoted so grep receives it. The source root is the specific lab folder, not your home directory or the system root. You should see four expected lines in events.log and one in workshop notes.log. The example notes file should be absent from the selected result set. If your local tool rejects the include option, compare a direct two-file search using the quoted paths.

grep -rHn --include='*.log' -F -e 'job=ws-17 ' -- "$GREP_LAB"

Know what recursion means before enabling it on an unfamiliar tree. With GNU grep, -r follows symbolic links explicitly given on the command line and ordinarily skips symlinks it encounters during recursive search. The uppercase -R follows recursive symlinks more broadly. A symbolic link is a path pointing to another path; it can lead outside the directory you intended or visit the same content through another name. Choose the narrow starting folder and explicit file paths when you can. Your system can implement optional behavior differently, so check that grep's manual.

As a mental check, draw the intended inputs before running a recursive command. The system could have compressed files, binary files or private data under the directory. A search that runs successfully on your text fixtures does not automatically apply to those inputs. GNU grep can report that a binary file matches rather than printing it as clean text. Use a tool suited to the data format and avoid putting raw binary or sensitive log snippets onto a shared terminal. Record which files were intentionally excluded.

Preview configuration text without claiming effective settings

A common learner task is to display a file without blank or comment lines. A comment can begin after spaces or tabs, so a pattern that only matches a hash at the very beginning misses indented comments. Build a new harmless text fixture with a heading comment, an indented comment, a whitespace-only line and two settings. The purpose is to read the retained text. No program parses this file, and the search never changes it. Do not treat its output as what an installed service will actually apply.

cat > "$GREP_LAB/workshop.conf" <<'CONF'
# Generated training note
    # Indented practice comment
    
workers 2
listen 8080
CONF
grep -nEv '^[[:space:]]*(#|$)' "$GREP_LAB/workshop.conf"

The inverted expression drops lines containing nothing except whitespace or a comment marker after leading whitespace. Expect lines four and five to be printed. In a real configuration file, inline comments, includes, defaults and conditional sections can matter. Filtering text is a read-only view. A service-specific parser or authorised diagnostic query can be needed to learn how a running instance interprets its configuration. Ask what the assignment actually needs before adding administrator permissions or trying to edit the configuration.

A line-number result documents the input used by the search. It does not validate that a service accepts a setting. For example, some settings apply in one context declared earlier and not in another. Other files may be loaded by an include directive. One file can also contain a line overridden by the program's effective configuration rules. If asked to report active settings, check the documented service method for that environment. Keep a text search and an effective configuration check listed as distinct operations.

Decide whether your count needs a field-aware reader

An HTTP access log can contain a status value, a resource path, address information and other free text. A search for the characters 404 can match a filename such as /404-guide even when the response status is 200. A quoted message or header can also contain that number. Check how the log configuration describes status and which field the question needs. A string search is effective for locating probable rows. A count that drives an incident report needs a method that matches the actual status field.

Compare three supplied lines in a small structured fixture. One returns status 404 for a schedule request. One returns status 200 for a documentation path containing the characters 404. A third returns status 200 and has a diagnostic note containing an apparent status value. If you search by raw substring, you will find all three. If you ask a parser to read the numeric status field and compare it to 404, the exact count is one. The number is only meaningful when the reader understands the data representation.

cat > "$GREP_LAB/access.jsonl" <<'JSONL'
{"path":"/schedule","status":404,"note":"missing file"}
{"path":"/404-guide","status":200,"note":"training article"}
{"path":"/notes","status":200,"note":"previous status=404"}
JSONL
grep -Fc '404' "$GREP_LAB/access.jsonl"
python3 - "$GREP_LAB/access.jsonl" <<'PY'
import json
import sys

with open(sys.argv[1], encoding="utf-8") as source:
    records = [json.loads(line) for line in source]
print(sum(record["status"] == 404 for record in records))
PY

On a machine with Python 3 the expected outputs are three from the literal grep count and one from the parsed comparison. This simple exercise is not a script to deploy against real log files. Actual logs may use different fields, missing values or several records on one line, and a production pipeline needs documented handling of invalid input. The example demonstrates that syntax matters. JSON lets one record contain both a structured numeric field and unrelated text with the same characters. A full incident summary can name both how the candidate lines were found and how the count was validated.

Select the time window and input before writing the pattern

The operator's morning report may have come after a log was rotated. Rotation gives a growing log a new file or archive so the current program can continue writing without keeping all history in one open file. Searching only the current filename can miss the hours you were asked to inspect. An empty match then describes the file you happened to read. It supplies little evidence about the desired event time. Confirm the stored log names, time range, service and format before choosing which input to search.

Work through a fictional split. The current file contains entries at 11:00 and later. The workshop failure was at 09:10. An older authorised file covers 08:00 through 10:59. Search the older fixture for the exact job marker and verify the timestamp fields in the selected rows. A search of the newer file can legitimately return no match. Retain the name of the file used and let the report say which data was covered. If times appear in different zones, convert the reported interval consistently before judging that a line was outside it.

Some services write to a system journal instead of a predictable plain-text file. A journal reader can limit output by service or time before passing authorised text to a matcher. A rotated archive can be compressed and require a suitable reader. Choose the tool appropriate to how the events were stored. Avoid reading every archived file to compensate for uncertainty about the requested period. In a real service, contact the authorised operator if you cannot determine which storage location and retention apply.

Check exact text assumptions when input crosses systems

A file can appear to contain the exact sample while storing different bytes. A carriage return at the end of a Windows-style line can affect an entire-line match in tools that keep it as part of the input. A non-ASCII letter can be represented by more than one byte. Two strings that look similar to a reader do not automatically have the same stored representation. When a full-line fixed match fails on a known fixture, examine a small safe copy and its representation before changing the source file.

Character classes and case conversion can depend on locale, which is the environment's rules for interpreting text. For a documented ASCII-only assignment, a predictable locale can help make a command reproducible across machines. For multilingual logs, keep the intended encoding and locale rather than treating all non-ASCII characters as noise. Start with two sample inputs whose equality you can explain. Document any deliberate normalization, such as removing a line-ending convention from a temporary copy, before relying on the changed text to count records.

Keep command correctness separate from the desired answer. A script can read every input successfully and match the wrong field with perfect consistency. To demonstrate your report works, include one example known to qualify and one plausible counterexample. The input, pattern, output and observed exit status together are enough evidence to explain the search. A quick visual scan that only notices familiar words does not provide that level of confidence.

Make a script report what the search actually discovered

A search can be part of a report that runs unattended. Plan for three outcomes before adding it. A matching record is one success. A known file with no selected record can be normal. A missing or unreadable file is a failure to observe, and the report should say so. Do not convert all nonzero statuses into “nothing found”. Make the search location and intended marker visible without printing any sensitive content in the report. In a real production workflow preserve the useful diagnostic under the appropriate permissions.

Here is a small pattern you can adapt after you run the earlier fixture. It checks the file contents with fixed matching and distinguishes the status before printing a summary. Run it using the fixture file before cleanup. Repeat with a marker you know is absent and an intentionally uncreated path. This example prints results from a known training file. For real logs replace the printed matching contents with a safe count or approved metadata if details are sensitive.

input_file="$GREP_LAB/events.log"
marker='job=ws-17 '
if grep -nF -e "$marker" -- "$input_file"; then
    printf 'Selected matching records from %s\n' "$input_file"
else
    status=$?
    if [ "$status" -eq 1 ]; then
        printf 'Read %s and selected no records\n' "$input_file"
    else
        printf 'Search error for %s (status %s)\n' "$input_file" "$status" >&2
    fi
fi

Check why the status is read immediately in the error branch. A separate assignment records the status from grep before another program or shell operation replaces it. A successful printed message has its own status and does not carry the original grep result. A full automation script can choose its own documented exit behavior based on whether no matches is acceptable. It can also confirm the input belongs to an approved time window. The shell check alone does not test whether your pattern correctly identifies an error class.

Think one step further when a search is piped into a formatter. The formatter can complete successfully even if grep returned an error. A pipeline's ordinary status may reflect the last command. A Bash setting such as pipefail can expose a failure from another stage, but a grep no-match status can be expected and still nonzero. Test known match, no-match and bad path cases. Choose how each result should appear before placing the command in a daily report. Keep tool exit rules and business meaning separate.

Now clean up the files you created. Print the saved temporary path and check it. This sequence removes only the two subdirectory files, the three files at the root and the two empty directories. If an unexpected file keeps a directory nonempty, inspect the contents rather than following with a recursive deletion. Stop after the exercise; there are no services to restart and no network resources to remove. Preserve only the sample output if your class needs the worksheet.

printf '%s\n' "$GREP_LAB"
rm -- "$GREP_LAB/team/workshop notes.log" "$GREP_LAB/team/example.txt"
rmdir -- "$GREP_LAB/team"
rm -- "$GREP_LAB/events.log" "$GREP_LAB/workshop.conf" "$GREP_LAB/access.jsonl"
rmdir -- "$GREP_LAB"

Interview practice and self-check

How do you search an error line when its case may differ?

I would first decide whether I need a literal word anywhere or a severity field in a particular position. For a broad literal search I could use fixed-string and ignore-case options. For the workshop severity I would match a known position and delimiter. I would test a line with the word embedded in the message and confirm it is not selected as a severity. This distinguishes finding clues from counting actual failure records.

Why does a dot in a filename change the result of a regex search?

An unescaped dot is a regular-expression operator that can match another character. A file named readings.csv can therefore be confused with readingsXcsv in the fixture. I would use fixed strings for the known name or escape appropriate pattern characters with the intended regex syntax. I would compare the two controlled lines so I can explain the result rather than hope the live file happens to contain no similar names.

How do you explain an empty grep result in a scheduled check?

I would inspect the exit status immediately and verify the intended path was readable. A normal no-match status and input error are different. If the command uses a pipeline, I would account for the status of the earlier search rather than trusting the final formatter. I would also verify the pattern on a known input before interpreting no matches as evidence that the service had no errors.

When is recursive text search a poor first step?

I would avoid starting at a broad directory that contains unrelated data, symbolic links or varied formats. I would identify the approved log root, filter relevant files and start with one known input. I would use filenames and line numbers to preserve provenance. If I need to find files by size, date or name before reading them, an appropriate file-search command can choose the inputs and grep can work on the contents afterwards.

Quick quiz

Two lines contain the marker, one of them twice. Which quantity does the matching-line count report?

Check your answer

Two selected lines. To count separate printed matches in a simple fixture, choose a mode that returns the actual matching pieces and count those under its documented behavior.

Your search found a warning line as context around an error in another job. What evidence should you use before attributing the warning to the failed import?

Check your answer

Compare the actual job identifier, timestamps and format. A context option selected nearby lines based only on their position relative to the match. It did not decide which operation they belong to.

A script sees no output for an absent input file. Should it report a clean log with no error marker?

Check your answer

It should report that reading or searching the intended input failed. The expected absence of a match is a separate outcome that requires a successful observation of the correct input.

Revision cards

Pattern choice

Pass fixed text as a literal. Use a regular expression when you need anchors, ranges or alternatives, and test it on a known nonmatch.

Keep provenance

Include filename and line position when a search spans several inputs. Use context for orientation and identifiers for correlation.

Three statuses

Distinguish match, no match and error. Use an immediate status check rather than assuming a blank terminal establishes a cause.

Count the right thing

Know whether you need selected lines, matched substrings, distinct jobs or exact structured records. Choose the method that can answer that question.

Primary references