Linux sed and awk Cheat Sheet

Edit text streams with sed and parse structured text with awk.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all

sed Substitution

Replace text patterns line by line.

Replace first occurrence per line

Substitute one match in each line.

bashANYsedreplace
bash
sed 's/foo/bar/' file.txt
Notes

By default, sed replaces only the first match on each line.

Replace all occurrences per line

Substitute every match on each line.

bashANYsedreplaceglobal
bash
sed 's/foo/bar/g' file.txt
Notes

The `g` flag applies the replacement globally across the line.

Edit a file in place

Modify the original file directly.

bashANYsedin-place
bash
sed -i 's/debug/info/g' app.conf
Notes

In-place editing is powerful; consider keeping backups before bulk changes.

Edit in place with backup

Create a backup copy while editing.

bashANYsedbackupin-place
bash
sed -i.bak 's/debug/info/g' app.conf
Notes

Creates `app.conf.bak` before replacing the original file.

Use an alternate delimiter

Make path replacements easier to read.

bashANYseddelimiterpaths
bash
sed 's|/usr/local/bin|/opt/bin|g' paths.txt
Notes

Alternate delimiters reduce escaping when replacing file paths or URLs.

sed Line Deletion and Printing

Delete, print, and filter lines by patterns or ranges.

Delete blank lines

Remove empty lines from output.

bashANYseddeleteblank-lines
bash
sed '/^$/d' file.txt
Notes

A common cleanup step before diffing or processing text.

Delete comment lines

Skip lines that begin with `#`.

bashANYseddeletecomments
bash
sed '/^[[:space:]]*#/d' config.ini
Notes

Especially useful for previewing meaningful config lines only.

Print only matching lines

Use sed as a pattern filter.

bashANYsedprintfilter
bash
sed -n '/ERROR/p' app.log
Notes

Suppress default output with `-n`, then explicitly print matches.

Delete a line range

Remove lines 5 through 10.

bashANYseddeleterange
bash
sed '5,10d' file.txt
Notes

Ranges are useful for removing generated headers or blocks quickly.

Print a line range only

Show lines 5 through 10.

bashANYsedprintrange
bash
sed -n '5,10p' file.txt
Notes

A compact way to inspect a specific segment of a file.

awk Fields and Records

Split lines into fields and work with structured text.

Print selected columns

Show the first and third whitespace-delimited fields.

bashANYawkfieldscolumns
bash
awk '{print $1, $3}' access.log
Notes

Awk automatically splits input lines into fields using whitespace by default.

Use a custom field separator

Split CSV-like data on commas.

bashANYawkcsvdelimiter
bash
awk -F, '{print $1, $2}' users.csv
Notes

`-F` sets the input field separator.

Print the last field

Use NF to reference the final field on each line.

bashANYawkfieldsnf
bash
awk '{print $NF}' file.txt
Notes

`NF` is the number of fields in the current record.

Print line numbers with lines

Prefix each line with NR.

bashANYawkline-numbernr
bash
awk '{print NR ": " $0}' file.txt
Notes

`NR` is the current record number across all input.

Set output field separator

Join output fields with commas.

bashANYawkofsformatting
bash
awk 'BEGIN{OFS=","} {print $1, $2, $3}' file.txt
Notes

`OFS` controls how fields are separated when printed with commas in `print`.

awk Filtering and Aggregation

Filter rows and calculate totals, counts, and summaries.

Print rows matching a condition

Show lines where column 3 is greater than 100.

bashANYawkfilter
bash
awk '$3 > 100 {print $0}' metrics.txt
Notes

Awk's pattern-action style is ideal for tabular filtering.

Sum a numeric column

Add all values in the second field.

bashANYawksumaggregation
bash
awk '{sum += $2} END {print sum}' prices.txt
Notes

Use the END block for final reporting after all input is processed.

Calculate an average

Compute the average of a numeric field.

bashANYawkaverageaggregation
bash
awk '{sum += $2; count += 1} END {if (count) print sum / count}' prices.txt
Notes

Track totals and counts explicitly for derived values like averages.

Count rows by key

Count occurrences of the first field.

bashANYawkgroupingcount
bash
awk '{count[$1]++} END {for (k in count) print k, count[k]}' file.txt
Notes

Associative arrays make awk a lightweight grouping and summarization tool.

Find the maximum value

Track the highest number in a field.

bashANYawkmaxaggregation
bash
awk 'NR==1 || $2 > max {max=$2} END {print max}' values.txt
Notes

Awk is often enough for lightweight numeric analysis without needing a spreadsheet.

awk Scripting Patterns

Use BEGIN, END, and built-in variables effectively.

Use BEGIN and END blocks

Print headers and footers around processed output.

bashANYawkbeginend
bash
awk 'BEGIN{print "name,total"} {print $1 "," $2} END{print "done"}' report.txt
Notes

BEGIN runs before input, END runs after all input is consumed.

Process command output

Filter output from another command using awk.

bashANYawkpipelinecommand-output
bash
df -h | awk 'NR>1 {print $1, $5, $6}'
Notes

Awk is especially useful for command output with stable columns.

Match with regex in awk

Print only lines that match a regex.

bashANYawkregexfilter
bash
awk '/ERROR|WARN/' app.log
Notes

A pattern-only awk program prints matching lines by default.

Replace text in awk

Use `sub` and `gsub` for replacements.

bashANYawkreplacegsub
bash
awk '{gsub(/foo/, "bar"); print}' file.txt
Notes

`sub` replaces one match, while `gsub` replaces all matches in the current record.

Skip a header row

Ignore the first line of a delimited file.

bashANYawkheadercsv
bash
awk 'NR>1 {print $1, $2}' users.csv
Notes

Skipping headers is one of the most common awk patterns for CSV-like inputs.

Recommended next

No recommendations yet.