Essential sed Commands for Text Processing

# Print the last line of a file
sed -n '$p' ok.txt

# Output total number of lines
sed -n '$=' ok.txt

# Count blank lines
sed -n '/^$/=' ok.txt

Line Selection and Printing

# Print odd-numbered lines (1st, 3rd, 5th, ...)
seq 10 | sed -n '1~2p'

# Print even-numbered lines (2nd, 4th, 6th, ...)
seq 10 | sed -n '2~2p'

Inserting Content

  • sed '5 a\123' ok.txt — Append 123 after line 5.
  • sed '5 i\123' ok.txt — Insert 123 before line 5.
  • sed '5 s/$/123/' ok.txt — Append 123 to the end of line 5.
  • sed '5 s/^/123/' ok.txt — Prepend 123 to the start of line 5.
  • sed '/FTP/i\123' ok.txt — Insert 123 before any line containing FTP.
  • sed '/FTP/a\123' ok.txt — Append 123 after any line containing FTP.

Deleting Lines

  • sed '1~2d' /etc/passwd — Delete every odd-numbered line starting from line 1.
  • sed '2~2d' /etc/passwd — Delete every even-numbered line starting from line 2.
  • sed "/user02/,+1d" qqqq.txt — Delete the line matching user02 and the next line.

Substituting Text

  • sed 's/root/ROOT/' t1 — Replace first occurrence of root on each line.
  • sed 's/root/ROOT/g' t1 — Replace all occurrences of root in the file.
  • sed '2s/root/ROOT/g' t1 — Replace all root instances only on line 2.
  • sed '2s/root/ROOT/' t1 — Replace first root on line 2.
  • sed '2s/root/ROOT/2' t1 — Replace only the second occurrence of root on line 2.
  • sed -n 's/root/ROOT/w /tx' t1 — Write modified lines (with substitution) to /tx.
  • sed 's/^/# /' t1 — Comment out every line by prepending # .

Utility Examples

Count word frequencies:

sed 's/ /\n/g' file.txt | sort | uniq -c

Remove specific characters (a, b, c, or d):

sed 's/[abcd]//g' test.txt

Wrap speicfic characters in double quotes:

sed 's/[abcd]/"&"/g' test.txt

Advanced Opreations

  • In-place editing with backup:
    sed -i.bak 's/123/efg/g' a.txt

  • Extract lines 1–8 into a new file:
    sed -n '1,8w user.txt' /etc/passwd

  • Insert contents of one file into another at line 2:
    sed -i '2 r readfile.txt' writefile.txt

Character Translation

Convert lowercase to uppercase using one-to-one mapping:

sed 'y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/' t1

Replace Antire Lines

Replace line 1 with ROOT:

sed '1c\ROOT' t1

Tags: sed text-processing command-line Linux Shell

Posted on Fri, 15 May 2026 06:49:01 +0000 by ghostrider1