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

Chapter 4: Linux Advanced Commands

AWS Cloud

4.3 Text processing: awk and sed

Friends, awk is the king of columns and sed is find-and-replace. Whether you need the top 10 IPs from Mauli Dairy's access log or want to change a port in a config, these two tools do the job.

awk — column-based processing

awk reads one line at a time by default and numbers its fields from $1. Its default split uses runs of whitespace as separators and ignores leading and trailing whitespace. Use -F when a known input format uses a different field separator.

# Use a readable sample in this known short log format: address status body_bytes
printf '%s\n' '192.0.2.10 200 512' '192.0.2.11 304 0' '192.0.2.10 200 1024' | awk '{print $1}' | sort | uniq -c | sort -rn | head -n 10

# Project account name and configured login shell from the local file
awk -F: '{print $1, $7}' /etc/passwd

# Sum response body bytes in the numeric third field of the sample format
printf '%s\n' '192.0.2.10 200 512' '192.0.2.11 304 0' '192.0.2.10 200 1024' | awk '{sum += $3} END {print sum, "bytes"}' 

sed — stream editor (find & replace)

# First match on each input line
printf '%s\n' 'port port label' | sed 's/port/listener/'
# Every nonoverlapping match on each input line
printf '%s\n' 'port port label' | sed 's/port/listener/g'
# Print only lines 10 through 20 of a readable text file you choose
sed -n '10,20p' file.txt
# Suppress lines starting with optional whitespace and a hash in the output
sed '/^[[:space:]]*#/d' file.txt

Test sed before using -i

Run sed without -i and save the candidate under a separate name. Compare it with the input and verify that only the intended lines changed.

Ravindra Bagale's Tip

Keep a copy of the original configuration. Generate the candidate separately and read the diff before applying it. Use the application's supported configuration check before reloading the service.

Lab

खाली दिलेल्या workshop lab मध्ये awk ने स्टेशनचे आकडे तपासा आणि sed ने सूचनेची वेगळी प्रत तयार करा. diff वापरून नेमकी कोणती ओळ बदलली ते तपासा.

Two requests from the workshop

The Mauli workshop records inspection runs in a text file. Each line gives a shift name, a station, the number of units tested, and the number that passed. The supervisor needs totals for a handover. There is also a separate notice with an outdated link to the inspection form. The supervisor wants to review one change to that notice before sending it. Both jobs involve text, but the first job depends on understanding the positions and meanings of values, while the second depends on controlling exactly what part of a sentence changes.

awk is a small programming language and a command that runs programs written in it. It reads records, divides them into fields, and runs instructions when a condition holds. A record is one unit of input. In this lesson each record is a line. A field is a value taken from a position within that record. Here field three always means units tested for that inspection run. You can tell awk to add field three over all runs, or add it separately for each station. The original log can remain untouched while awk produces a report.

sed reads text through a series of editing instructions. The program might keep lines in a range, remove comments from the output, or substitute a new link on a particular line. It sends the resulting text to standard output by default, the same ordinary channel other commands use for their results. On an interactive terminal the output usually appears on the screen. Keeping this default makes it possible to compare a preview against the original before anyone publishes the notice.

Use a Bash shell on a Linux machine for the following lab. An EC2 Linux instance works if you already have one, and so does an ordinary local Linux environment. The files and numbers are fictional, and no network connection, administrator permission, or live application is required. The quoted blocks create a new scratch directory and files with fixed contents. Work in the same shell because the variable storing the directory lives there. If you need to resume after closing the terminal, make a fresh fixture so that the example starts from known input.

text_lab=$(mktemp -d) || exit 1
printf 'Lab directory: %s\n' "$text_lab"
cat > "$text_lab/runs.txt" <<'RUNS'
shift station tested passed
morning press-a 12 11
morning   press-b   8   8
evening press-a 10 9
evening press-b 5 3
RUNS
cat "$text_lab/runs.txt"

The directory printed on your machine is generated for this run. The remaining output contains five lines. The first is a header naming the four values. The third contains extra spaces around its fields so that you can watch how the default split behaves. cat sends the file contents to the terminal without removing those spaces. The shell's > places the here-document text in the new fixture file. The quoted marker tells the shell to preserve the characters in that text. Keep the two marker lines as shown, with RUNS on its own line at the end.

Read the data manually once before running any analysis. The two morning runs tested 12 and 8 units, for a total of 20. They passed 11 and 8, for a total of 19. The two evening runs tested 10 and 5 and passed 9 and 3. Across all four runs, that gives 35 tested and 31 passed, with four failures. At press A there were 22 tested and 20 passed. At press B there were 13 tested and 11 passed. Those independent hand calculations give you expected values against which to check each command.

Read one record before reading all records

Start with a program that prints each record's position, field count, and original text. NR is the number of records read so far. NF is the number of fields in the current record. $0 means the whole current record, including the ordinary spaces within it. $1 means the first field. $NF uses the value of the field count as a field number, so it means the last field. When this file has four fields, $NF and $4 pick the same value. Awk counts fields from one, with the whole record assigned the special zero.

awk '{print NR, NF, $0}' "$text_lab/runs.txt"
1 4 shift station tested passed
2 4 morning press-a 12 11
3 4 morning   press-b   8   8
4 4 evening press-a 10 9
5 4 evening press-b 5 3

The first two numbers come from awk. The rest of each output line comes from the original record. The spaces within the original press B morning line remain visible in $0. The default field separator still treats each run of spaces or tabs as a boundary between words, with leading and trailing whitespace ignored for splitting. This is why that same line has a field count of four. If you need an empty field to represent missing data, a whitespace-separated format of this kind cannot tell an empty field apart from another set of spaces. Choose a format whose separator can represent an empty value, or define an explicit marker for missing data.

awk 'NR == 3 {print "station=" $2, "passed=" $NF}' "$text_lab/runs.txt"
awk 'NR > 1 {print $1, $2, $4}' "$text_lab/runs.txt"
station=press-b passed=8
morning press-a 11
morning press-b 8
evening press-a 9
evening press-b 3

Each instruction has an optional condition followed by an action in braces. Without a condition, awk runs the action on every record. NR == 3 runs the action only on the third input record, with the header counted as record one. NR > 1 runs on the four rows after the header. Use two equals signs when testing equality. A single equals sign assigns a variable or field, which can change a later decision in the program. Awk evaluates statements within an action in sequence, making it possible to select a row and then perform several calculations with it.

The single quotes around the program are shell quoting, which keeps the shell from expanding awk's $1 and $NF. Awk receives the text and interprets those fields. The double quotes around the filename belong to the shell too, but they let the shell expand the directory variable while preserving its entire value as one argument. In the program, the double quotes around "station=" mark literal text for awk. Adjacent expressions such as "station=" $2 join without a separator. A comma in print separates expressions with the current output separator, a space here, and print automatically ends the output line.

Try replacing the display request with awk 'NR == 3 {print $0; print $1, $2, $3, $4}' "$text_lab/runs.txt". The first printed version shows the source record with its spacing, and the second prints four extracted values with one separator between them. This is helpful when preparing a consistently spaced report. It also explains why reassembling extracted fields is unsuitable when the original spacing carries meaning. Use the entire original record when you intend to preserve it.

Awk may also rebuild its whole record when you assign a new value to a field. For example, in awk '{$2 = "checked"; print $0}', each output record is assembled with the updated second field and the configured output field separator. This changes the emitted text, while the input file remains as it was. If an untouched first line or the spacing of an existing file is part of the requirement, test the complete output before choosing such a transformation.

Turn a practical question into a field test

Suppose the supervisor wants to inspect any individual run with two or more failed units before discussing station totals. The threshold is a number of units per run, and the difference of fields three and four gives that number. Both evening runs used the same shift label, so filtering for the evening shift alone would give one extra row. The threshold makes the selection directly reflect the stated question.

minimum=2
awk -v limit="$minimum" '
    NR > 1 && ($3 - $4) >= limit {
        printf "%s %s failed=%d\n", $1, $2, $3 - $4
    }
' "$text_lab/runs.txt"
evening press-b failed=2

The shell expands "$minimum" as part of the assignment argument to -v. Awk calls the received variable limit. Keep the program single-quoted, with settings passed separately. This keeps command syntax and data in separate places and makes a threshold easy to change between runs. If you send arbitrary text through -v, know that awk can interpret backslash escape sequences in assignment values. The example's integer threshold avoids that uncertainty. If a person supplies the threshold, check that it is an integer in the expected range before running the report.

The double ampersand inside the awk program means both conditions must hold. The first condition skips the header. The parentheses show the arithmetic being compared. printf takes a format string and values to fill it. Each %s formats a string, the shift and station in this case. %d formats an integer. \n requests a newline because awk's printf adds none on its own. The format is fixed and the station is an argument. That matters if a label contains percent signs, because it should be displayed verbatim without becoming the format string.

Trace all four records once. Morning press A has 12 minus 11, which is one. Morning press B has eight minus eight, which is zero. Evening press A has ten minus nine, which is one. Evening press B has five minus three, which is two. A run with exactly two failures is included because the test allows equality. Changing the threshold to three should give no output. That result means none of the fixture rows met the criterion. To interpret a blank result from real data, also check that the input was read, has the expected rows, and gives a successful command status. Awk can successfully produce an empty report.

For a filename containing a path you did not make yourself, first ensure it refers to the intended readable regular file. In an awk argument list, a bare name like zone=east can be interpreted as a variable assignment. Prefix a relative file of that form with ./, or use an absolute path. All files in this lab resolve under the scratch directory and include a slash. These argument details are separate from the splitting that awk performs on the contents after opening the file.

Keep a running total and check its inputs

The next report counts tested and passed units over the whole file. A running total is a variable that starts at zero and grows whenever a new value arrives. Awk's BEGIN action runs before the first record, and its END action runs after input processing. In the middle action we verify the simple input format and add the two numbers. The format for this file is four whitespace-separated values, with nonnegative whole numbers in the last two positions and a passed count that never exceeds the tested count. This is a lab data contract. Without assumptions about the format, the third value has no reliable meaning.

cat > "$text_lab/totals.awk" <<'AWK'
BEGIN { rows = tested = passed = bad = 0 }
NR == 1 {
    if (NF != 4 || $1 != "shift" || $2 != "station" ||
        $3 != "tested" || $4 != "passed")
        bad++
    next
}
NF != 4 || $3 !~ /^[0-9]+$/ || $4 !~ /^[0-9]+$/ || $4 + 0 > $3 + 0 {
    bad++
    next
}
{
    rows++
    tested += $3
    passed += $4
}
END {
    if (bad || !rows || !tested) {
        printf "report unavailable: valid rows=%d invalid records=%d tested=%d\n", rows, bad, tested
        exit 2
    }
    printf "runs=%d tested=%d passed=%d failed=%d pass=%.1f%%\n",
           rows, tested, passed, tested - passed, 100 * passed / tested
}
AWK
awk -f "$text_lab/totals.awk" "$text_lab/runs.txt"
runs=4 tested=35 passed=31 failed=4 pass=88.6%

The file ending in .awk stores the program separately from the data. The operating system does not assign special meaning to that suffix. The -f flag tells awk to read the program from that file. Storing a multi-step program this way makes it easier to see what changed when reviewing a revision. The next command skips all remaining rules for the current record and continues with the following input record. Thus the header is checked and skipped, an invalid row is counted and skipped, and the unguarded accumulation action sees only valid measurements.

The part between slashes is a regular expression, a pattern for checking the characters of a string. A leading caret and trailing dollar sign mark the start and end of the field. The bracket range describes a digit, and the plus sign requires one or more. The operator !~ means the field fails to match that pattern. The additions of zero in the comparison force numeric interpretation. For this small fixture all integers fit comfortably within awk's numeric range. Very large counters, rounding rules for payments, and decimal precision are design choices to address separately before using the same approach for other data.

After the first two data rows, the totals are 20 tested and 19 passed. After adding evening press A they are 30 tested and 28 passed. The final row brings them to 35 and 31. Multiplying the fraction by 100 converts it to a percentage, and %.1f formats the result with one decimal place. The doubled percent sign emits a literal percent sign. A simple mean of four pass percentages would give each of the four runs the same weight. Here every unit should carry the same weight, so the correct calculation divides all passed units by all tested units. The number you present has consequences for the supervisor's next decision, so state the calculation as well as the answer.

Try a deliberate data failure. Create a second copy with one impossible measurement and then rerun the same program. $? is the shell's most recent command status, so save or print it before running another command. The message goes to ordinary output in this self-contained training script. A report consumer must check the status before accepting the content. The program picks status two to mark unusable data. Other conditions, including cases where awk itself cannot open a file, can also yield a nonzero status, so keep any diagnostic message when investigating.

cp "$text_lab/runs.txt" "$text_lab/bad-runs.txt"
printf 'night press-a 2 7\n' >> "$text_lab/bad-runs.txt"
awk -f "$text_lab/totals.awk" "$text_lab/bad-runs.txt"
printf 'status=%s\n' "$?"

head -n 1 "$text_lab/runs.txt" > "$text_lab/empty-runs.txt"
awk -f "$text_lab/totals.awk" "$text_lab/empty-runs.txt"
printf 'status=%s\n' "$?"
report unavailable: valid rows=4 invalid records=1 tested=35
status=2
report unavailable: valid rows=0 invalid records=0 tested=0
status=2

In the first case values from the four valid records were read, but there is one invalid row, so a normal-looking final total would be misleading. In the second case the header was recognized and there were no data records. In a third case you can leave several valid rows with zero tested units, in which case dividing by tested would still be invalid. The guard covers both empty and zero-denominator inputs. Notice that zero passed can be a real outcome when some units were tested. Give it separate treatment from missing measurements.

Group and compare stations

A single total answers the handover question for the workshop, but it cannot tell you which station should be investigated first. To report each station separately, keep a collection of totals indexed by station name. An awk associative array is such a collection with keys such as press-a and press-b. When a record arrives for press B, the program updates only the totals whose key is press B. In the following exercise use the already validated fixture. The short projection assumes the format established above and is not an alternate validation script for unfamiliar files.

awk '
    NR > 1 {
        tested[$2] += $3
        passed[$2] += $4
    }
    END {
        for (station in tested)
            printf "%s tested=%d passed=%d failed=%d\n",
                   station, tested[station], passed[station],
                   tested[station] - passed[station]
    }
' "$text_lab/runs.txt" | LC_ALL=C sort
press-a tested=22 passed=20 failed=2
press-b tested=13 passed=11 failed=2

The first row initializes the press A totals to 12 tested and 11 passed as far as those additions are concerned. The second data row initializes press B. The third and fourth update those already existing keys. The loop at the end visits each key present in the tested array. Its iteration order is unspecified, so the pipe sends the resulting lines to sort. LC_ALL=C asks that sort use predictable byte ordering in this exercise. The prefix before the sort command applies to that command only. Sorting by station name makes repeated displays easier to compare even if awk happens to visit keys in a different order.

Both stations had two failures, while they tested different numbers of units. If you need to decide which station had the larger share of failures in these samples, compare two out of 22 with two out of 13. An observation involving only four runs is a reason to inspect more data, while a decision about the station's normal performance needs additional evidence such as different workloads, equipment settings, and the test period. The command provides clean arithmetic tied to particular rows.

Grouped reports store one entry per distinct key. A station list of two needs little memory. A distinct key of one request identifier per line in a huge log could require a large collection. Ask what group gives you a meaningful answer before selecting an identifier. Likewise, two records with the same station text but different spelling will become separate groups. Before forcing labels to lowercase or changing punctuation, check whether they represent the same station in the source system.

When reading two files, NR continues across them and FNR starts again with each new file. If both files contain a header, a rule with FNR == 1 { next } skips the header of each. A rule with NR == 1 { next } skips the very first header only. This distinction explains a report that works on one shift file but mixes headers into calculations when you give the command a morning file and a separate evening file. If a header is optional, use a documented format or verify the first record instead of dropping it just because it is first.

Define the input format before choosing a separator

The station file works with default splitting because a shift and station are single words, every count is present, and spaces are just separators. Other formats give those characters a different role. Awk's -F sets its input separator. When empty positions matter, try a training file with a visible delimiter before attempting the exercise on the exported data. Each record below has a station, a descriptive label, and a count. The second label is empty. A colon marks each boundary, and a description is permitted to contain spaces.

printf '%s\n' 'press-a:main frame:22' 'press-b::13' > "$text_lab/stations.txt"
awk -F: '{printf "%s label=[%s] count=%s fields=%d\n", $1, $2, $3, NF}' "$text_lab/stations.txt"
press-a label=[main frame] count=22 fields=3
press-b label=[] count=13 fields=3

Awk recognizes an empty field between the two adjacent colons. Field three remains the count. This works because the label cannot itself contain a colon under the lab format. The moment someone enters main:west frame as the second value, the split produces four fields and the second and third positions no longer mean the same things. You must either reject such values at the writer or use a format that represents a delimiter inside a value and an appropriate reader for it.

CSV is a family of comma-separated text formats. In a commonly used CSV format, quoting a value lets it include commas and newlines. That makes CSV different from a simple split at every comma. To see the failure, make a new file representing a spreadsheet export. Station and count still belong to each record, and the second value now contains a comma.

cat > "$text_lab/export.csv" <<'CSV'
station,description,count
press-a,"main frame, west wall",22
press-b,"near wash area",13
CSV
awk -F, 'NR > 1 {printf "%s field3=[%s] fields=%d\n", $1, $3, NF}' "$text_lab/export.csv"
press-a field3=[ west wall"] fields=4
press-b field3=[13] fields=3

Nothing in -F, tracks when a delimiter is inside a quoted value. The first data row is split into four fields and the count appears in field four. The second row happens to give the intended count. Testing only the second row would incorrectly validate the tool choice. Input that looks simple on a terminal often contains a special case after a few thousand rows, so keep small examples that specifically exercise quotes, empty values, and delimiters inside data.

If Python 3 is available, its standard library has a CSV reader. The code below reads each row using the headers as field names and uses integer conversion for the documented count. The reader tracks quoting rules and accepts a file opened with newline="", which lets the CSV parser handle line boundaries itself. A CSV export with a different delimiter or quoting convention needs parameters that match the writer. In this exercise the fixture uses commas and double quotes. The earlier awk report remains appropriate for the four-field plain text runs file.

python3 - "$text_lab/export.csv" <<'PY'
import csv
import sys

with open(sys.argv[1], newline="", encoding="utf-8") as source:
    for row in csv.DictReader(source):
        print(f"{row['station']} count={int(row['count'])} description={row['description']}")
PY
press-a count=22 description=main frame, west wall
press-b count=13 description=near wash area

There are also versions of GNU awk with a dedicated CSV mode. Read the documentation for the version installed on your system before assuming the mode is present. The basic awk command on a Linux image can be a different implementation. It is fine for the lab's whitespace and colon formats. Using a format-specific mode or a CSV parser gives you a clear behavior for the quoted comma, where a plain field separator alone cannot respect the intended boundary. Separately check the number and type of values before accepting a real export as complete.

A server log presents the same question about format in a different form. In the standard Nginx combined format, the first value is the remote address and a later value records the response body bytes. Some values are quoted and have variable content, including an HTTP request line and a user agent. Check the actual log format definition before assuming field numbers. In a format that logs an upstream response, a missing value can be shown as a dash. Converting that dash into zero for arithmetic turns absence into an observed measurement. Define how to count missing values separately so a report reader can judge the total.

If a reverse proxy sits in front of the server, the recorded remote address can describe that proxy. Counting each value is still a valid count of the addresses in the file. Interpreting the results as unique customers requires knowing the network and logging configuration, and one customer can have a changing or shared address. State what your report actually counts so a numerical result does not become a stronger claim in the handover.

Preview a small, precise edit with sed

The second request starts with a notice. It contains the form address to update, a commented historical address, and a note with an address that should stay as it is. The replacement must be restricted to the setting whose key is form. Treat the notice as data in a scratch file. You do not need a web server, and none of the dummy hostnames in the notice will be visited.

cat > "$text_lab/notice.txt" <<'NOTICE'
title=Handover worksheet
# form=http://forms.example.test/archive
form=http://forms.example.test/daily
note=Keep http://docs.example.test/guide for the printed instructions
NOTICE
sed 's|^form=http://forms\.example\.test/daily$|form=https://forms.example.test/daily|' "$text_lab/notice.txt"
title=Handover worksheet
# form=http://forms.example.test/archive
form=https://forms.example.test/daily
note=Keep http://docs.example.test/guide for the printed instructions

On each normal cycle sed reads the next line into a temporary work area called the pattern space, applies the program, and normally prints that area. The s command substitutes a replacement for a match. This program uses a vertical bar to separate the pattern and replacement instead of a slash because the address itself has slashes. It anchors the pattern to the beginning and end of the whole original line. The backslash before each dot tells the regular expression to look for an actual dot. A bare dot is a regular expression metacharacter that can match other individual characters.

The program leaves the original scratch file untouched. You can confirm that by reading it again with cat "$text_lab/notice.txt". A change you see on the screen is only a proposed output. A broad expression such as s/http/https/g would change the comment and note, and on another run it could match the start of a string already beginning with https. The anchored version has a testable purpose and a clear condition for doing nothing: when the exact old setting is absent, it emits the input unchanged.

By default a substitution affects the first match in each applicable line. The trailing g flag repeats it for all nonoverlapping matches in that pattern space. To isolate the difference, pipe a single line into sed. Each command receives its own complete input line, so the second result does not depend on the first.

printf '%s\n' 'red red blue' | sed 's/red/green/'
printf '%s\n' 'red red blue' | sed 's/red/green/g'
printf '%s\n' 'tray=red red' | sed 's/red/[&]/g'
printf '%s\n' 'tray=red' | sed 's/red/blue\&green/'
green red blue
green green blue
tray=[red] [red]
tray=blue&green

In the replacement, an ampersand inserts the text matched by the pattern. In the third command this produces brackets around each red token. To write an actual ampersand into the replacement, escape it with a backslash as in the fourth command. The command is single-quoted so the shell preserves the backslash. If you build replacements from values supplied by other people or programs, the replacement might itself contain the delimiter, backslashes, or ampersands. Use a parser or another method with a literal data parameter when those characters are allowed, or validate and escape the input for this exact replacement syntax before passing it to sed.

To print just a few rows of ordinary line-based input, use sed -n '2,3p' "$text_lab/notice.txt". The -n option suppresses automatic printing. The range includes lines two and three, and p explicitly prints them. Leaving out -n prints each selected line twice because both p and the normal end of the cycle emit it. An address can also be a pattern, as in sed -n '/^form=/p' "$text_lab/notice.txt". This pair of slashes surrounds the condition selecting a line. The final p says what to do on those lines. No substitution is involved.

An instruction such as sed '/^[[:space:]]*#/d' "$text_lab/notice.txt" drops lines starting with a hash after optional whitespace from the output. The letter d ends processing of the current pattern space and continues with the next record, so it skips printing that line. Check the input syntax before dropping all such rows. Some formats have meaningful markers beginning with a hash. Where you are editing only a form address, there is no benefit in removing the comment and losing its history.

Decide from the difference, then verify the candidate

Save a candidate under its own name. The redirection writes to that new path. Shells typically open an output file, truncating its existing contents, before starting the command. If you mistakenly use the input name for the output, a preview with no in-place option can still destroy the input. The next command uses the names notice.txt and notice.candidate.txt. Make the separation part of every preview you run.

sed 's|^form=http://forms\.example\.test/daily$|form=https://forms.example.test/daily|' \
  "$text_lab/notice.txt" > "$text_lab/notice.candidate.txt"
diff -u "$text_lab/notice.txt" "$text_lab/notice.candidate.txt"
printf 'diff status=%s\n' "$?"
@@ -1,4 +1,4 @@
 title=Handover worksheet
 # form=http://forms.example.test/archive
-form=http://forms.example.test/daily
+form=https://forms.example.test/daily
 note=Keep http://docs.example.test/guide for the printed instructions
diff status=1

The diff also prints two file headers whose timestamps and paths depend on your run. A minus and plus on the two form lines show the exact replacement. The adjacent unchanged lines make it clear that the comment and note survived. For diff, status zero means equal, one means different, and a greater value means a comparison problem under the standard convention. In this fixture one is the expected status. It would mean a different thing from one returned by a command that uses status for ordinary failure. Read the documentation of each tool before deciding which status a script should accept. With Bash's errexit enabled, do this comparison in an explicit condition or the shell can exit before your status print.

An exact-line check on the candidate gives separate evidence of the settings that should appear after the edit. Read the desired new line, list all active form lines, and compare the resulting line count with one. Testing only that the new address appears somewhere would pass even if the notice contains two active settings. Testing only the count gives no evidence about the address. The handover requirement needs both conditions.

grep -Fx -- 'form=https://forms.example.test/daily' "$text_lab/notice.candidate.txt"
awk '/^form=/ { count++ } END { print "active form settings=" count + 0 }' \
  "$text_lab/notice.candidate.txt"
form=https://forms.example.test/daily
active form settings=1

To validate the original was never used as the destination, run grep -Fx -- 'form=http://forms.example.test/daily' "$text_lab/notice.txt". It prints the old setting. If you run the narrowly scoped edit on the candidate into a third file, the content should stay the same. The pattern matches only the exact old setting, so a second run has nothing further to change. This exercise illustrates idempotence for a text transformation, meaning that after one application produces the expected result, applying it again has the same result. Idempotence alone does not prove correctness. A pattern that never matches would also appear idempotent.

GNU sed supports an in-place editing option with an optional backup suffix. Its replacement writes a temporary file and renames it to the requested filename when complete. That mechanism changes which file the path points to and can matter for symbolic links, which are filesystem references to other paths. Option syntax is implementation-specific. For example, leaving out the backup suffix has different invocation syntax across GNU and some BSD implementations. This lab uses a separate output so you can keep the original and review a diff on either. If you eventually use an in-place option from your own manual, work on a new disposable regular file first and verify the backup path and behavior before relying on it.

In real application work a valid line is only one part of a valid configuration. You need the application to check the syntax of the complete configuration, including any included files, and you need a documented way to apply and roll back the reviewed change. A replacement that appears to work can conflict with another listen directive or a setting elsewhere. The training notice has no running application attached. Practice inspecting the candidate here so you keep working evidence when the same workflow is applied to a configuration on an authorized server.

Produce a reviewed handover

For the first checkpoint, run the total program on the original five-line file, and confirm that every report number can be traced to its inputs. Then change only the training copy or start from a fresh lab. For a new exercise use a copy containing a fifth run, night press-b 7 6. Before running the tools, write the expected totals on paper. After the new row press B has 20 tested and 17 passed. The entire file has 42 tested and 37 passed, with five failed and a rounded pass rate of 88.1 percent. Check both perspectives, because a correct workshop total paired with a wrong station report can still misdirect the discussion.

For the second checkpoint, have a classmate alter the copy of the notice so the active form key is form_backup. The precise program should then leave the changed training copy as it is. Read this outcome as a precondition failure for the edit request, because there was no exact active old form setting. With the original fixture restored, run the preview again, find one changed line in the diff, and apply the two candidate checks. Make a note of the original and candidate paths alongside your conclusion so a reviewer can repeat the exact comparison.

If awk reports the wrong field count, print NR, NF, and the complete record for a few representative lines. Check which separator the actual writer used. If the file was saved with Windows line endings, a carriage return can remain at the end of a field and fail an exact match; displaying the bytes with od -c on a tiny local fixture can confirm that before you decide how to handle the source format. If an awk program unexpectedly receives no field references, review the shell quotes. If sed prints the old form line with no message, check the anchors and the exact source bytes. Lack of a matching substitution is a successful sed run in ordinary cases. Interpret the result using the expected difference.

Before cleaning up, check the displayed directory name and confirm it is from the first command in this lesson. The cleanup below removes only recognized fixture files. If you made additional practice copies, list the directory and remove those specific files after reviewing their names. rmdir refuses a nonempty directory, which keeps the contents available if you forgot a file. Close or move any other shell with that directory as its working directory before removing it.

if [ -n "${text_lab:-}" ] && [ -d "$text_lab" ]; then
  printf 'Removing lesson fixtures from %s\n' "$text_lab"
  rm -- "$text_lab/runs.txt" "$text_lab/totals.awk" "$text_lab/bad-runs.txt" \
    "$text_lab/empty-runs.txt" "$text_lab/stations.txt" "$text_lab/export.csv" \
    "$text_lab/notice.txt" "$text_lab/notice.candidate.txt"
  rmdir -- "$text_lab"
fi

If you skipped an optional exercise, a missing fixture can cause a harmless file-not-found message during this explicit cleanup. If the directory is still present, identify what remains by listing it. A lab cleanup should never delete unrelated files simply because they happen to share a folder.

Explain the result before moving on

Interview question. How do you choose between awk and sed here?

Start by naming the task. When asked for failed units by station, describe field three minus field four and the separate totals keyed by station. Awk's record, field, condition, and aggregation model matches that computation. When asked to update a single active form setting, describe the current expected line, the new line, and every neighboring line that must be preserved. Sed's addressed substitution can produce a candidate while leaving the original available for comparison. Explain the input assumptions as part of the choice, especially for exports that need a separate parser.

Interview question. Why display the field count before calculating?

A program that adds the third field assumes that every data row really stores a number there. A renamed header, a new column, or a quoted delimiter can make the count or meaning change while the command still executes. Showing the input record and field count lets you catch inconsistencies on representative data. Validating the format detects them while processing the complete report. For example, press A's CSV description contains a comma, so an ordinary comma split shows four fields in what is logically a three-field record.

Quiz. Should you average the four per-run percentages to report the percentage of all units that passed?

Use 31 divided by 35, multiplied by 100, and round as required. Each unit contributes the same weight to that calculation. A simple average of four percentages gives the run of five units the same weight as the run of twelve, answering a different question. You should be able to explain whether your unit of observation is a run, a station, or a single inspected unit before choosing a denominator.

Quiz. The candidate has the new form address twice and sed returned zero. Is the edit ready?

The handover calls for exactly one active form setting. A successfully executed substitution can affect more than one record. List the active settings and count them before accepting the candidate, then review why the source contained two matching lines. Compare against the original to find the scope of the edit. The status tells you about running the tool, while the count and diff tell you about the resulting text.

Quiz. Which record counter skips a repeated header in each of two known input files?

Use FNR == 1 to identify the first record of each file. NR is cumulative, so it identifies only the first record from the first nonempty file at one. If a report sometimes consumes a headerless file, detect or validate the expected first record before skipping it. Otherwise genuine data can be lost while the final calculation still looks plausible.

Revision cards

Original record or extracted value

Ask whether you need the text exactly as read or a particular value within it. Use the original record for context and fields for labeled positions. The field count helps show whether those positions match the expected layout.

Check the calculation and the evidence

A report that says 88.6 percent should also tell you that 31 of 35 inspected units passed. The counts reveal scaling, denominator mistakes, and the effect of small samples.

Preview, compare, verify

Send sed output to a separate candidate, compare against the original, and check for the exact expected setting and number of settings. A successfully run command is the start of verification.

Primary references