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

How to Configure HTTP/HTTPS Proxy on Linux and Windows (CLI, GUI, Registry, and APT)

Set up proxy access correctly on Windows and Linux for command-line tools, package managers, and system-level use. This guide covers quick commands, persistent configuration, and common troubleshooting steps.

Read More

Linux pmap Command Guide: Inspect Process Memory Maps with Practical Examples

Learn how to use the Linux pmap command to inspect per-process memory mappings, compare output modes, and troubleshoot high memory usage quickly. This updated guide includes workflow steps, command examples, and interpretation tips.

Read More

iostat Command Guide for Linux: 20 Practical Examples for CPU and Disk I/O Troubleshooting

Learn how to use iostat to monitor CPU and storage performance on Linux systems. This revised guide covers installation, 20 practical commands, metric interpretation, and a troubleshooting workflow.

Read More

xargs in Linux: Practical Commands, Safe Patterns, and Pipeline Workflows

This guide explains how to use xargs effectively in Linux/Unix shells, from basic stdin handling to safe file operations and parallel execution. You’ll learn practical command patterns, portability caveats, and safer alternatives.

Read More

Linux mount and umount Commands: Practical Examples, /etc/fstab, and Safe Unmounting

Learn how to mount and unmount filesystems reliably on Linux, from one-off commands to persistent /etc/fstab entries. This guide covers common filesystem types, command comparisons, and safe troubleshooting steps.

Read More

How to Use gsh to Run Linux Commands Across Multiple Servers

gsh (Group Shell) lets you execute one command across many Linux hosts from a single terminal. This guide explains host grouping with /etc/ghosts, core options, and practical command patterns.

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