Course Info / Syllabus

Labs

Lecture Topics

Exam Reviews

Source Code & Other Resources


Operating Systems Concepts & Design

Grep, sed, and awk

When to use which


1. grep: The Search Engine

grep (Global Regular Expression Print) is used to find lines that match a specific pattern. It’s your “Find” command on steroids.

Simple Demos:

Pro Tip: Piping to grep

You’ll often use grep to filter the output of other commands using the pipe |:

# List all files, but only show the .pdf ones
ls -l | grep ".pdf"


2. sed: The Stream Editor

sed is used to transform or edit text. While it can do many things, its most common use is “search and replace.”

The basic syntax:

sed 's/old_text/new_text/' filename

Simple Demos:


Use grep, then sed

Imagine you have a configuration file, and you want to find all lines related to “Port” and change the port from 8080 to 9000.

# First, use grep to see what we are working with
grep "Port" config.sys

# Now, use sed to change it
sed -i 's/8080/9000/g' config.sys

The Power of RegEx

Both commands use Regular Expressions (RegEx). For example:

5. awk - pattern scanning and processing language

By default, awk sees every line as a collection of fields separated by whitespace.

The Basics: Printing Columns

awk uses $1, $2, etc., to refer to the first, second, or -th column. $0 refers to the entire line.

# Example input: "John Doe 25"
echo "John Doe 25" | awk '{print $1, $3}'
# Output: John 25


Changing the Delimiter (-F)

If your data isn’t separated by spaces (like a CSV or the system /etc/passwd file), you tell awk what the “Field Separator” is using -F.

# Print the usernames from the system password file (separated by :)
awk -F ":" '{print $1}' /etc/passwd


Filtering and Math

awk is actually a full programming language, so it can do things grep can’t, like checking if a number in a specific column is greater than a certain value.


Built-in Variables: NR and NF

# Print the line number followed by the first column
awk '{print NR, $1}' list.txt

# Print only lines that have exactly 3 columns
awk 'NF == 3' list.txt

Resources for grep, sed, and awk

Challenges