# 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— Append123after line 5.sed '5 i\123' ok.txt— Insert123before line 5.sed '5 s/$/123/' ok.txt— Append123to the end of line 5.sed '5 s/^/123/' ok.txt— Prepend123to the start of line 5.sed '/FTP/i\123' ok.txt— Insert123before any line containingFTP.sed '/FTP/a\123' ok.txt— Append123after any line containingFTP.
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 matchinguser02and the next line.
Substituting Text
sed 's/root/ROOT/' t1— Replace first occurrence ofrooton each line.sed 's/root/ROOT/g' t1— Replace all occurrences ofrootin the file.sed '2s/root/ROOT/g' t1— Replace allrootinstances only on line 2.sed '2s/root/ROOT/' t1— Replace firstrooton line 2.sed '2s/root/ROOT/2' t1— Replace only the second occurrence ofrooton 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