Linux Foundations / Find Evidence in Files

Search text with literal and basic patterns

Lesson 14 of 37. Open to read. No account needed.

A search can return plausible lines while answering the wrong question. A dot in an error marker might be treated as pattern syntax; a different letter case might hide a record; a missing file might be mistaken for a file with no matches. Start by stating the exact text or relationship you want, then compare the result with known source evidence.

You will inspect a small synthetic task log, search literal markers first, and then use a few basic pattern rules deliberately. Your independent task will save a different marker's evidence while preserving the original log. No system log or directory-wide scan is needed.

1. Supply a known, owned log

Complete Use variables and inspect command lookup first, including its session cleanup. Work as the ordinary Bash user in the checked Ubuntu guest. Run each command one line at a time and inspect its result before continuing. Stop on unexpected errors; the no-match and missing- input observations below are intentional and identified before execution.

Use the taught identity and origin checks:

id -u
id -un
ps -p $ -o comm=
type printf set mkdir grep cat ls rm rmdir

Require a nonzero user ID, the expected account and Bash. printf and set should be Bash builtins; the utilities must use their expected guest executables. Preserve an understood color-only listing alias. If grep is the ordinary alias adding only --color=auto, that option changes display color when appropriate, not the matching request. The -a option of type lists all command matches, including aliases and functions, rather than only the first resolution. Inspect them before accepting a color alias, which could otherwise hide a same-named function:

type -a grep

Require only the understood --color=auto alias, if present, and expected guest executable paths. Stop for any function, builtin, other alias argument or unrecognized entry. Then use the already taught forced external lookup:

type -P grep

Require the expected guest GNU grep executable. Both inspections are needed; -P alone does not exclude a function behind an alias. Preserve the accepted color-only alias and compare text/line numbers rather than color. Reconcile other findings before searching; do not erase the session configuration.

Use the taught read-only option listing:

set -o

Require errexit off so the planned no-match and missing-input observations do not end an altered practice shell. Preserve a different setting and reconcile the declared setup; do not change it here.

The task owns ~/linux-practice/search-text-evidence/. Check the parents and the prospective exercise entry without trailing slashes:

ls -ld ~
ls -ld ~/linux-practice
ls -ld ~/linux-practice/search-text-evidence

Require ordinary parent directories, shown with leading d, owned by the recorded account. Stop on links, unexpected ownership or an unrecognized path. The exercise entry must be absent for a fresh start. If it exists, use the resume section rather than writing over its contents.

After confirming absence, create and inspect only that directory:

mkdir ~/linux-practice/search-text-evidence
ls -ld ~/linux-practice/search-text-evidence

Require its expected identity before the separate location check:

cd ~/linux-practice/search-text-evidence
pwd
ls -a

Require the recorded practice-root path followed by /search-text-evidence, and only . and .. in the inventory. Do not create the fixture from a different location.

Ten newline-terminated records

The taught printf '%s\n' format prints each quoted argument with a newline. The ten supplied strings form ten complete records, with no blank record. The taught > creates the new task-log.txt; its name must be absent before this first write. All data is synthetic:

printf '%s\n' 'START delivery audit' 'INFO task=load code=READY' 'ERROR task=label code=E.42' 'INFO note=retry E.42 after review' 'ERROR task=route code=EX42' 'error task=sort code=E.42' 'WARN task=pack code=W.07' 'WARN task=seal code=WX07' 'INFO task=archive code=W.07' 'END delivery audit' > task-log.txt

Inspect the saved file and its complete contents:

ls -ld -- task-log.txt
cat task-log.txt
ls -a

Require an ordinary regular file, shown with leading -, one link and your recorded owner. It must contain exactly:

START delivery audit
INFO task=load code=READY
ERROR task=label code=E.42
INFO note=retry E.42 after review
ERROR task=route code=EX42
error task=sort code=E.42
WARN task=pack code=W.07
WARN task=seal code=WX07
INFO task=archive code=W.07
END delivery audit

Count the positions from one to ten for your first predictions. Do not add those numbers to the file. Keep the source unchanged throughout the searches. missing-log.txt remains absent for a later diagnostic; marker-results.txt is a separate future output for the independent task.

2. Search literal text before interpreting patterns

grep selects lines whose text matches its search request and writes those lines to stdout. -F chooses fixed-string matching: characters in the search text, including punctuation, are treated literally. A match can occur anywhere in a line; it does not require the entire line to equal the marker. Default matching is case-sensitive.

In the forms here, -- ends option parsing, the next operand is the search text, and the following operand is the one file to read. Single quotes keep the search text together and prevent Bash from treating its characters as shell syntax. They do not choose grep's matching mode; -F does that.

Predict which source lines contain the exact marker E.42:

grep -F -- 'E.42' task-log.txt

Expect the complete records at positions 3, 4 and 6. The EX42 record does not contain a literal dot, so it is excluded. The INFO note does contain the literal marker, so it is included. A marker search does not independently classify every returned line as a failed task.

-n prefixes each selected line with its one-based source line number. It does not renumber the matches from one, and it does not edit the source. Add that evidence to the same fixed search:

grep -F -n -- 'E.42' task-log.txt

For this unchanged one-file fixture, expect:

3:ERROR task=label code=E.42
4:INFO note=retry E.42 after review
6:error task=sort code=E.42

The prefix before each colon is a source position. The remainder is the original matched line. Check the full text as well as the numbers; a changed source would change the evidence those numbers refer to.

3. Make the case decision explicit

Search for the literal uppercase text ERROR first:

grep -F -n -- 'ERROR' task-log.txt

Expect lines 3 and 5. The lowercase error on line 6 differs, so the default case-sensitive search excludes it.

-i requests case-insensitive matching. It changes how case is compared, not what text is printed: grep retains the original line's case. Predict the additional evidence before adding the option:

grep -F -n -i -- 'ERROR' task-log.txt

For these supplied ASCII records, expect lines 3, 5 and 6. The last output line still starts with lowercase error. Use case-insensitive search when that matches the question; do not add it automatically whenever a result is missing. Case behavior for other languages needs its own data and locale consideration; this fixture does not claim to cover those rules.

4. Choose a basic pattern only for an intended relationship

Without -F, the normal grep mode used here interprets a basic regular expression. It is a small language for matching text relationships. This lesson uses only three punctuation rules:

Pattern syntaxMeaning in the shown basic patterns
.Match any one character within a line. It is not automatically a literal dot.
Leading ^Require the following match to begin at the start of the line.
Trailing $Require the preceding match to end at the end of the line.

The quotes still protect the argument from Bash. They do not stop grep from interpreting regular-expression punctuation. This pattern matching is also different from Bash filename expansion: grep is examining text within the specified file, not expanding a filename pattern into path arguments.

Compare the earlier literal marker with this intentionally broader pattern:

grep -n -- 'E.42' task-log.txt

Expect lines 3, 4, 5 and 6. The dot can match the literal . in E.42 or the X in EX42, so line 5 joins the results. Quoting 'E.42' did not make the dot literal to grep. For an exact code, select -F instead of accepting the extra record as close enough.

Anchors answer a different question. Predict the records that begin with the uppercase text ERROR:

grep -n -- '^ERROR' task-log.txt

Expect lines 3 and 5. The leading caret establishes where the match begins; it does not make the search case-insensitive or imply a field boundary after the word. For example, a different source line beginning ERRORS could also match this prefix pattern.

Use both anchors for this exact complete line:

grep -n -- '^START delivery audit
#x27; task-log.txt

Expect only 1:START delivery audit. The anchors require the start and end of the line around the supplied text. The pattern contains no wildcard between its words. In fixed-string mode, those same ^ and $ characters would be literal characters to find, rather than anchors. Always name the mode as part of your explanation.

5. Separate no match from an error

For the GNU grep forms used here, with no quiet-mode shortcut, these statuses have different meanings:

StatusMeaning for this task
0At least one line was selected without a search error.
1The search completed but selected no lines.
2An error occurred, such as the deliberately missing input below.

Use the status parameter already taught in the pipeline lesson. Run its printf immediately after grep; another command would replace $?. First ask for a marker known to be absent from this valid input:

grep -F -n -- 'CANCELLED' task-log.txt
printf 'grep status: %s\n' "$?"

Expect no selected lines and status 1, without a missing-file diagnostic. That is useful negative evidence about this searched input and marker, not proof about every log on the machine.

Now confirm missing-log.txt remains absent in ls -a. Predict the result of requesting the same marker from that nonexistent input:

grep -F -n -- 'E.42' missing-log.txt
printf 'grep status: %s\n' "$?"

Expect a diagnostic naming missing-log.txt on stderr and status 2. An illustrative English explanation is No such file or directory; the exact wording and language can vary. This result does not say that a valid log was searched and contained no marker. The requested input was unavailable.

Finally, compare the known matching case:

grep -F -n -- 'E.42' task-log.txt
printf 'grep status: %s\n' "$?"

Expect the three known numbered records and status 0. The status complements those records; it does not tell you whether the chosen marker answered your intended question. The status-printing printf is itself another command, so a later $? would describe that newer command instead.

Diagnose before broadening the search

ObservationPossible explanationSafe next check
Too many code matches appear.Regex punctuation broadened the request, or the marker also occurs in notes.Compare exact source text and -F versus basic-pattern mode.
The lowercase record is missing.The search was case-sensitive.Decide whether case should matter before adding -i.
The right text appears at an unexpected position.-n refers to the current source, which may differ from the fixture.Read the complete unchanged input and compare its record order.
No selected lines appear with status 1.No line matched this request in the valid searched input.Inspect spelling, actual contents, case and chosen mode.
No selected lines appear with status 2.An input or another search operation failed.Read stderr and inspect the exact owned filename; do not call it zero matching data.
An anchored pattern matches more than the expected word.A start anchor establishes position, not a complete-word boundary.Compare the full text and the actual relationship required.

Independent task: preserve the warning-marker evidence

Keep the original source unchanged. Recheck the exact exercise path, source identity and all ten records. Require marker-results.txt absent before its first creation; reject an existing, linked or unrecognized output. The desired marker is the exact string W.07, including its dot.

Before opening the answer:

  1. Find the records containing that literal marker, including their source line numbers. Predict which records qualify before running the search.
  2. Save that numbered evidence in the separate marker-results.txt using the already taught output redirection. Check the immediate grep status, then inspect the saved file and its entire contents.
  3. Compare with a read-only basic-pattern search for 'W.07' without -F. Identify the extra record and explain the punctuation rule that admits it.
  4. Confirm the source still matches all ten original records and that missing-log.txt remains absent.

Success: the saved evidence contains only source lines 7 and 9 with their complete original text; the literal search reports 0; the deliberately broader pattern also admits line 8. The file is a recognized owned regular single-link output, distinct from the unchanged input.

The previous redirection lesson's warning still applies: > opens its output before grep searches. Never use task-log.txt as the result destination. A no-match or error result would not protect an output from truncation.

Graduated hints

  1. The requirement is an exact marker, not a request for any character between W and 07. Choose the matching mode first.
  2. Include -n so the saved records retain their source positions. Keep the new result filename separate from the input and inspect it after writing.
  3. Combine the fixed marker 'W.07', input task-log.txt and the taught > marker-results.txt. For the comparison, remove only -F, without redirecting over the saved literal evidence.

Answer and Reasoning

From the verified exercise directory, with the unchanged source and fresh result name confirmed, one valid extraction is:

grep -F -n -- 'W.07' task-log.txt > marker-results.txt
printf 'grep status: %s\n' "$?"

Expect status 0. The selected lines went to the output file, so their absence from the terminal is explained by redirection. Inspect the saved evidence:

ls -ld -- marker-results.txt
cat marker-results.txt

Require the expected ordinary owned single-link output containing exactly:

7:WARN task=pack code=W.07
9:INFO task=archive code=W.07

The second line belongs because it contains the marker, even though it begins with INFO. The task asked for a marker, not only lines labelled WARN. A different search that silently excludes that record does not meet the same requirement.

Now compare the intentionally broader text pattern without replacing the saved result:

grep -n -- 'W.07' task-log.txt

It selects lines 7, 8 and 9. Line 8 has WX07, whose X satisfies the single regex dot. The full quoted pattern remains one shell argument in both modes; grep's interpretation of the dot changes because -F is absent.

Recheck the source and inventory:

cat task-log.txt
ls -a

The original ten lines remain unchanged, and no missing-input file was created. Valid alternative inspection choices must preserve the same exact literal result, source positions and data; a plausible count or status alone cannot replace the content comparison.

For the status check, CANCELLED in the valid log selected nothing and gave 1, while the missing log prevented the intended search and gave 2 with a diagnostic. For the anchor check, ^ and $ constrained line positions only in basic-pattern mode. Those differences explain why changing flags without first reading the evidence can answer a different question.

Cleanup after the independent task

Finish all predictions and comparisons before removing any file. Recheck the shared root and exercise entries, rejecting links or unexpected owners:

ls -ld ~/linux-practice
ls -ld ~/linux-practice/search-text-evidence

Enter and verify separately from removal:

cd ~/linux-practice/search-text-evidence
pwd

Require the exact recorded exercise path. Inspect the inventory and the two expected files:

ls -a
ls -ld -- task-log.txt marker-results.txt

Require only the two known regular single-link files owned by the recorded user, plus dot entries. Recheck any contents you cannot identify. Preserve unrecognized entries; the intentionally missing name is not a removal target.

The shown y/n responses assume English confirmations. Establish the actual program's documented responses before removal, and stop if the language or response convention is unclear. Only after those checks:

rm -i -- task-log.txt marker-results.txt

Approve only the known files. If stopping, decline the current and every remaining prompt; one n does not cancel later prompts. Inspect ls -a and require only . and .. before removing the directory.

Return to the shared root and verify its exact path first:

cd ~/linux-practice
pwd

Require the recorded shared-root path, then inspect the exercise entry:

ls -ld -- search-text-evidence

Only for the recognized owned empty directory:

rmdir -- search-text-evidence
ls -a

Retain the shared root and other lesson directories. No system logs, shell settings or external resources need restoring.

Resume without rewriting the evidence

After an interruption, recheck the ordinary guest, command origins, option baseline, directory identities and exact location. Inspect saved source and result contents to identify the last completed step. The numbered evidence belongs to that specific unchanged source.

Read-only searches can be repeated after the same input checks. Do not rerun the redirected extraction over an existing result without first recognizing and inspecting it. To recreate that owned result deliberately, use the taught named interactive removal after its metadata/content checks, confirm it absent, then extract from the preserved original source again.

For a complete restart, remove only recognized task files actually created, using the same guarded procedure. Leave unknown entries untouched, rebuild a fresh empty exercise directory, and supply the exact ten-line source again. Do not add a missing file or change marker spelling simply to silence an expected diagnostic.

Sources and other study views

The selected guest uses GNU grep 3.11. The upstream grep 3.12 manual is a companion for the bounded longstanding forms taught here, not a claim that every newer feature is available in 3.11. The same course version boundaries apply to Bash 5.2 and Coreutils 9.4.

Revision reconstructs the matching decisions; Quick Reference retrieves the taught patterns after study.

Study this course with an account

Course access adds revision notes, the Quick Reference, saved progress, bookmarks and your own notes.

INR 99 plus 18% GST. 90 days of online access. No auto-renewal.

See course access

This website is operated by VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED, operating as Vectametric.

Corporate Identity Number (CIN): U85499KA2026OPC229822. GSTIN: 29AAMCV8281D1ZS. Registered office: RS NO/38/2A/1 BASTAND, ROAD MAHANTESH NAGAR, Ramdurg, Ramdurg, Belgaum- 591123, Karnataka.

Queries and grievances: Prajval Honnungar, Grievance Officer and Data Protection Contact.

Telephone: +91 94800 09310. Support: support@vectametric.com. Grievances: support@vectametric.com.

Copyright 2026 VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED. All rights reserved.

Vectametric home · Roadmaps · Vecta IT Exams · Vecta Government Exams · Vecta Banking & Finance Exams · Vecta Entrance Exams · About us · Contact · Privacy Policy · Terms and Conditions · No-Refund Policy