Skip to content
Unit 3 Syllabus Note· Unix and Shell Programming

Unix and Shell Programming

Comprehensive exam revision notes for BCA-204N Unit 3 (Special Tools, Filters & Stream Editors (grep, sed, awk)). Includes Section A (2M), Section B (5M), and Section C (15M) questions, answers, and diagrams.

Unix and Shell Programming

Special Tools, Filters & Stream Editors (grep, sed, awk)

Core Definitions & Key Concepts

What are the three Standard I/O streams in Unix and their numeric file descriptors

  • `stdin` (Standard Input): File descriptor 0 (default: keyboard).
  • `stdout` (Standard Output): File descriptor 1 (default: terminal screen).
  • `stderr` (Standard Error): File descriptor 2 (default: terminal screen).

The difference between > and >> output redirection operators

  • >: Overwrites the destination file (truncates existing contents to 0 before writing).
  • >>: Appends new output data to the end of the file without deleting existing contents.

What does a Pipe (|) do in Unix

A Pipe connects the Standard Output (stdout) of the command on its left directly into the Standard Input (stdin) of the command on its right via kernel memory buffer.

What is the purpose of the tee command

tee reads standard input and writes it simultaneously to both standard output (screen) and to one or more files, splitting the stream like a plumbing T-junction.

grep, egrep, and fgrep

  • grep: Global Regular Expression Print using Basic Regular Expressions (BRE).
  • egrep: Extended grep (grep -E), supporting extended operators (+, ?, |, ()).
  • fgrep: Fixed/Fast grep (grep -F), searches literal strings without regex interpretation.

What do the regex anchors ^ and $ represent

  • ^: Matches the beginning of a line (e.g., ^Error matches lines starting with 'Error').
  • $: Matches the end of a line (e.g., done$ matches lines ending with 'done').

What is sed in Unix

sed (Stream Editor) is a non-interactive text editor that transforms streams of text line-by-line using scripted commands (substitution, deletion, insertion).

What are $0, $1, NR, and NF in awk

  • $0: The entire current line/record.
  • $1, $2: The first and second field/column on the current line.
  • NR: Number of Records (current line number processed so far).
  • NF: Number of Fields (count of columns on the current line).

Conceptual & Architectural Analysis

Standard Unix Text Filters: cut, paste, sort, uniq, and tr with Examples

Core Unix Text Processing Filters

System Architecture / Concept DiagramHorizontal Scroll Enabled
# 1. cut: Extracts specific byte/field columns
cut -d":" -f1,7 /etc/passwd    # Extracts username and login shell from /etc/passwd

# 2. paste: Merges lines of files side-by-side
paste names.txt marks.txt     # Column 1 = names, Column 2 = marks

# 3. sort: Sorts text lines alphabetically or numerically
sort -t":" -k3 -n /etc/passwd # Sorts by 3rd column (UID) numerically (-n)

# 4. uniq: Filters out adjacent duplicate lines (input must be sorted first!)
sort raw_ips.txt | uniq -c    # Counts unique IP occurrences

# 5. tr: Translates or deletes characters
cat file.txt | tr 'a-z' 'A-Z' # Converts lowercase to uppercase
cat text.txt | tr -d '\r'     # Deletes Windows carriage return characters

grep Flags and Common Regular Expression Patterns

grep OptionFunctionality
-iCase-insensitive matching
-vInvert match (prints lines that do NOT match pattern)
-nPrints line numbers along with matching lines
-cPrints count of matching lines only
-lPrints only names of files containing matches
-r / -RRecursively searches all files in subdirectories
-EUses Extended Regular Expressions (ERE)
-wMatches whole words only

sed Architecture and Common Transformation Commands

sed Execution Architecture

sed operates on a Pattern Space buffer:

  1. Reads one line from input into Pattern Space.
  2. Executes all matched editing commands in order.
  3. Flushes Pattern Space to stdout (unless -n is set) and repeats for next line.
BASH
1# Substitution: s/find/replace/flags
2sed 's/BCA/MCA/g' report.txt # Replaces all BCA with MCA globally
3sed -i 's/2023/2024/g' config.txt # In-place file modification
4
5# Deletion: d
6sed '1d' data.csv # Deletes line 1 (header row)
7sed '/^$/d' document.txt # Deletes all blank lines
8
9# Printing specific line ranges: -n and p
10sed -n '10,25p' server.log # Prints lines 10 through 25 only

The Structure of an awk Program with Built-in Variables

Structure of an awk Script

An awk program consists of three optional sections:

AWK
1BEGIN { # Executed ONCE before any input lines are read
2 FS = ":"; OFS = "\t"; print "USER", "SHELL"
3}
4{ # Executed FOR EVERY LINE in input stream
5 if ($3 >= 1000) print $1, $7
6}
7END { # Executed ONCE after all lines have been processed
8 print "Total users processed:", NR
9}
  • FS: Field Separator (default space/tab).
  • OFS: Output Field Separator.
  • RS / ORS: Record Separators.

In-Depth Analysis & Implementation

Develop a Complete Data Extraction Script in awk to Process /etc/passwd and Generate Formatted User Reports

System Architecture / Concept DiagramHorizontal Scroll Enabled
#!/usr/bin/awk -f
# University Examination Model Solution: Unit 3
# Advanced Awk Report Generator for Unix User Accounts

BEGIN {
    FS = ":"
    print "================================================================="
    print "            MJPRU UNIX SYSTEM USER ACCOUNTS REPORT"
    print "================================================================="
    printf "%-15s | %-6s | %-6s | %-25s\n", "USERNAME", "UID", "GID", "LOGIN SHELL"
    print "-----------------------------------------------------------------"
    system_users = 0
    regular_users = 0
}

# Pattern Matching: Skip comments
!/^#/ && NF >= 7 {
    username = $1
    uid = $3
    gid = $4
    shell = $7

    # Classify regular user vs system service user
    if (uid >= 1000 && uid < 65534) {
        regular_users++
        printf "%-15s | %-6d | %-6d | %-25s [USER]\n", username, uid, gid, shell
    } else {
        system_users++
        printf "%-15s | %-6d | %-6d | %-25s [SYSTEM]\n", username, uid, gid, shell
    }
}

END {
    print "================================================================="
    print "SUMMARY STATISTICS:"
    printf "Total System Service Accounts: %d\n", system_users
    printf "Total Regular Human Accounts:  %d\n", regular_users
    printf "Grand Total Lines Processed:   %d\n", NR
    print "================================================================="
}

Demonstrate Advanced Log Analysis using a Pipeline of Unix Filters (cat, grep, awk, sort, uniq)

System Architecture / Concept DiagramHorizontal Scroll Enabled
# Practical Scenario: Apache/Nginx Web Server Access Log Analysis
# Goal: Find Top 10 IP addresses making requests, along with request count

cat /var/log/nginx/access.log \
  | awk '{print $1}' \
  | sort \
  | uniq -c \
  | sort -nr \
  | head -n 10

# Explanation of the Pipeline:
# 1. cat access.log    : Streams raw web server log
# 2. awk '{print $1}'  : Extracts the first column (Client IP address)
# 3. sort              : Sorts IPs so duplicate IPs become adjacent for uniq
# 4. uniq -c           : Counts occurrences of each unique IP address
# 5. sort -nr          : Sorts numerically (-n) in reverse (-r) order (highest count first)
# 6. head -n 10        : Displays top 10 most frequent visitor IPs

# Bonus: Find all HTTP 404 Not Found errors
grep " 404 " /var/log/nginx/access.log | awk '{print $7}' | sort | uniq -c | sort -nr

sed Multi-line Pattern Space Editing, Hold Space, and Scripting with Practical Examples

Advanced sed: Pattern Space vs Hold Space

sed maintains two memory buffers:

  1. Pattern Space: Working buffer where current line is modified.
  2. Hold Space: Auxiliary persistent scratchpad buffer where text can be saved and retrieved across lines.
BASH
1# Key Hold Space Commands:
2# h : Copy Pattern Space to Hold Space (overwrites hold)
3# H : Append Pattern Space to Hold Space
4# g : Copy Hold Space to Pattern Space (overwrites pattern)
5# G : Append Hold Space to Pattern Space
6# x : Exchange contents of Pattern Space and Hold Space
7
8# Example 1: Reversing order of lines in a file (emulating 'tac')
9sed -n '1!G;h;$p' sample.txt
10# Explanation:
11# 1!G : For all lines except line 1, append Hold Space to Pattern Space
12# h : Copy new combination to Hold Space
13# $p : On the last line ($), print the Pattern Space
14
15# Example 2: Double-spacing a single-spaced file
16sed 'G' file.txt
17
18# Example 3: Print only lines that match pattern and the line immediately following it
19sed -n '/CRITICAL/{n;p}' server.log

Important Exam Points & Quick Revision

Practice writing awk scripts with BEGIN/END and building complex command pipelines (grep | awk | sort | uniq -c).

Your reading progress
0%

100% left on this page — finishing it closes the gap for Special Tools, Filters & Stream Editors (grep, sed, awk).

Weak topic hint

Special Tools, Filters & Stream Editors (grep, sed, awk) still counts as a weak topic until you finish this note and answer its questions.

Practise this unit
What Should You Do Next?

Test Your Understanding

Now that you've read through these notes, practice unit MCQs to identify weak points and solidify your learning before exams.