MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

UNIX sed Quick Reference: Print and Delete Lines with Address and Pattern Ranges

Originally published on 2010-11-23; fully revised and updated.

sed is a non-interactive stream editor used to process text line by line. This guide is for DevOps engineers and sysadmins who need fast, repeatable ways to select or remove lines in logs, config files, and shell pipelines.

unix-sed-quick-reference

What sed does in Unix automation

sed reads from standard input or a file, applies commands, and writes to standard output. Internally, it works with a pattern space for the current line and an optional hold space for temporary storage across cycles.

  • Use p to print selected lines (usually with -n).
  • Use d to delete selected lines from output.
  • Use addresses (line numbers, ranges, regex) to target exactly what should be processed.

How a sed execution cycle works

sed processes input one cycle at a time: read a line into pattern space, run commands, print (unless suppressed), then continue. If d is executed, sed skips printing for that cycle and immediately moves to the next line.

flowchart TD
    A[Start cycle] --> B[Read next line into pattern space]
    B --> C[Apply addressed commands]
    C --> D{Did d command run}
    D -- yes --> E[Skip printing and continue]
    D -- no --> F{Is auto print active}
    F -- yes --> G[Print pattern space]
    F -- no --> H[Only explicit p prints]
    E --> I{More input lines}
    G --> I
    H --> I
    I -- yes --> B
    I -- no --> J[Exit]

Create the sample file used in these examples

cat > sample.txt <<'EOF'
1. Linux - Sysadmin, Scripting etc.
2. Databases - Oracle, mySQL etc.
3. Hardware
4. Security (Firewall, Network, Online Security etc)
5. Storage
6. Cool gadgets and websites
7. Productivity (Too many technologies to explore)
8. Website Design
9. Software Development
10.Windows- Sysadmin, reboot etc.
EOF

nl -ba sample.txtCode language: JavaScript (javascript)

Print targeted lines with -n and p

When using p, pass -n to suppress automatic printing; otherwise matching lines can appear twice.

Address formExampleWhat it selectsPortability
Nsed -n '3p' sample.txtOnly line NPOSIX
M~Nsed -n '3~2p' sample.txtEvery Nth line starting at MGNU extension
M,Nsed -n '4,8p' sample.txtInclusive numeric rangePOSIX
$sed -n '$p' sample.txtLast linePOSIX
N,$sed -n '4,$p' sample.txtFrom line N to endPOSIX
/PATTERN/sed -n '/Sysadmin/p' sample.txtLines matching regexPOSIX
/PATTERN/,Nsed -n '/Hardware/,6p' sample.txtFrom first regex match through line NPOSIX
N,/PATTERN/sed -n '3,/Security/p' sample.txtFrom line N through first later regex matchPOSIX
/PATTERN/,$sed -n '/Website/,$p' sample.txtFrom regex match to endPOSIX
/PATTERN/,+Nsed -n '/Storage/,+2p' sample.txtMatched line plus next N linesGNU extension
/P1/,/P2/sed -n '/Storage/,/Design/p' sample.txtRange between two regex matchesPOSIX
# Print exactly line 3
sed -n '3p' sample.txt
# 3. Hardware

# Print every second line starting from line 3 (GNU sed)
sed -n '3~2p' sample.txt
# 3. Hardware
# 5. Storage
# 7. Productivity (Too many technologies to explore)
# 9. Software Development

# Print lines containing Sysadmin
sed -n '/Sysadmin/p' sample.txt
# 1. Linux - Sysadmin, Scripting etc.
# 10.Windows- Sysadmin, reboot etc.

# Print from Storage through Design (inclusive)
sed -n '/Storage/,/Design/p' sample.txt
# 5. Storage
# 6. Cool gadgets and websites
# 7. Productivity (Too many technologies to explore)
# 8. Website DesignCode language: PHP (php)

Delete lines with d using the same address patterns

d is effectively the inverse of p for many workflows: it removes matching lines from output and immediately starts the next sed cycle.

GoalPrint selectorDelete selector
Nth linesed -n '3p' sample.txtsed '3d' sample.txt
Range of linessed -n '4,8p' sample.txtsed '4,8d' sample.txt
Last linesed -n '$p' sample.txtsed '$d' sample.txt
Regex matchessed -n '/Sysadmin/p' sample.txtsed '/Sysadmin/d' sample.txt
Match to end of filesed -n '/Website/,$p' sample.txtsed '/Website/,$d' sample.txt
Blank linessed -n '/^$/p' sample.txtsed '/^$/d' sample.txt
# Delete line 3
sed '3d' sample.txt

# Delete lines 4 through 8
sed '4,8d' sample.txt

# Delete all lines containing Sysadmin
sed '/Sysadmin/d' sample.txt

# Delete from Website to end of file
sed '/Website/,$d' sample.txt

# Delete blank lines
sed '/^$/d' sample.txtCode language: PHP (php)

GNU sed extensions and portability notes

Most basic address forms are portable, but some compact selectors are GNU-only. If your scripts run across Linux and macOS/BSD systems, validate syntax before production rollout.

FeaturePOSIX sedGNU sedBSD/macOS sed
Basic addresses (N, M,N, $, /re/)YesYesYes
M~N step addressingNoYesNo
/re/,+N relative rangeNoYesNo
-i in-place edit without suffixNot standardizedYesNo (use empty or explicit suffix)
# Cross-platform friendly in-place edit with backup
sed -i.bak '/^$/d' sample.txt

# Portable fallback without -i
sed '/^$/d' sample.txt > sample.txt.tmp && mv sample.txt.tmp sample.txtCode language: PHP (php)

Best practices

  • Start with read-only commands (-n + p) before applying destructive edits.
  • Prefer single-quoted sed scripts in shell to avoid accidental variable expansion.
  • Remember sed uses basic regular expressions by default.
  • Use backups (-i.bak) or temp files for safe bulk edits.
  • Document GNU-only syntax in scripts to prevent cross-platform surprises.

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services — all in one place.

Explore Hospitals
I'm Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms. I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.

Related Posts

Jenkins Email-ext: Add Full or Regex-Filtered Build Logs to Email Body

Learn how to include Jenkins build logs directly in notification emails using email-ext tokens. This revised guide covers full-log and regex-filtered approaches for freestyle jobs and Pipeline templates.

Read More

Jenkins Email-ext: Include Build Logs in Email Body (Full Log or Regex-Filtered)

Learn how to configure Jenkins Email Extension tokens to send either the full build log or targeted regex matches directly in the email body. This guide covers practical token examples, workflow, and pitfalls to avoid noisy or oversized alerts.

Read More

Perl Punctuation and Sigils: Practical Symbol Reference with Examples

A clear reference to the punctuation marks you see most often in Perl code, including sigils, operators, delimiters, and quote forms. Includes usage tables, example snippets, and a quick decision flow for choosing the right sigil.

Read More

Perl Training for DevOps and Build Engineers: Updated Course Guide and Curriculum

This revised guide converts an older Perl training announcement into a practical reference for engineering teams. It summarizes the course format, curriculum, tooling, lab examples, and enrollment details that should be validated before booking.

Read More

Perl Interview Questions for DevOps Engineers: Practical Concepts, Commands, and Clear Answers

A cleaned-up, interview-focused Perl guide for DevOps and SRE roles. It covers one-liners, scope rules, references, regex, module loading, and command execution with practical examples.

Read More

Unix Epoch Timestamp Guide for DevOps: Conversions, Commands, and Pitfalls

Unix epoch timestamps are simple in concept but easy to misuse in production. This updated guide shows reliable conversions across shell, Python, JavaScript, and SQL, with timezone and Y2038 guardrails.

Read More
Subscribe
Notify of
guest
1 Comment
Newest
Oldest Most Voted
Puja kushwaha
Puja kushwaha
27 days ago

The sed command is very useful for editing text and processing files quickly in Unix. Practicing substitutions, line selection, and pattern matching can save time during routine tasks. It is wise to test complex expressions on a sample file before changing important data. Using clear patterns and careful quoting also helps avoid unexpected results. These habits make sed scripts easier to trust and reuse in automation workflows.

1
0
Would love your thoughts, please comment.x
()
x