Find the Best Cosmetic Hospitals

Explore trusted cosmetic hospitals and make a confident choice for your transformation.

“Invest in yourself — your confidence is always worth it.”

Explore Cosmetic Hospitals

Start your journey today — compare options in one place.

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

Linux System Administrator Responsibilities: Daily Operations, Privileges, and Best Practices

Linux system administrators are responsible for server reliability, security, access control, patching, backups, and troubleshooting. This updated guide maps those responsibilities to practical workflows and command examples.

Read More

Common UNIX Commands and Utilities: Practical Reference for DevOps and Sysadmin Work

A structured UNIX command reference organized by real operational tasks: discovery, files, processes, networking, text processing, and job control. Includes C-shell notes, comparison tables, and practical command examples.

Read More

Install Subversion (SVN) on Linux: Package Install, Source Build, Apache Setup, and Authentication

Learn how to install Subversion on Linux, create a repository, and publish it through Apache with user authentication. This revised guide includes both package-based and legacy source-build paths with practical commands.

Read More

Unix grep Quick Reference: Patterns, Options, and Real Command Examples

grep is the core Unix command for searching text by pattern across files or standard input. This revised quick reference covers syntax, high-value options, and practical examples you can use immediately.

Read More

Apache Ant: Set the Current User Home Directory with env.HOME (and Safe Fallbacks)

Learn how to read the logged-in user’s home directory in Ant using env.HOME, then make it portable with a user.home fallback. Includes build.xml patterns you can use in local builds and CI.

Read More

Unix Basics for DevOps Engineers: Commands, Permissions, Pipes, and Workflow

This revised guide turns a legacy Unix slide embed into a practical reference for beginners and DevOps engineers. Learn core Unix concepts, essential commands, and command execution flow with hands-on examples.

Read More
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
0
Would love your thoughts, please comment.x
()
x