sed

>Usage

sed (Stream Editor) is a text transformation wizard that modifies your text on the fly. Think of it as a mini production line where your text flows through, and sed applies changes as the text passes by – whether it’s replacing words, deleting lines, or inserting new content. It’s your go-to tool for automated text surgery!

>Synopsis

sed [OPTIONS] 'SCRIPT' [INPUTFILE...]

>Options

-i

-i (in-place): Makes changes directly to files, like editing a document with a permanent marker.

Example 1:

Dots

-zsh

> echo "old text" > file.txt
> sed -i 's/old/new/' file.txt
> cat file.txt


new text

-e

-e (expression): Allows multiple transformations in one go.

Example 2:

Dots

-zsh

> echo "The old gray dog" > file.txt
> sed -e 's/old/young/' -e 's/gray/brown/' file.txt


The young brown dog

-n

-n (quiet): Only shows what you specifically ask to see, like a stealth mode for text processing.

Example 3:

Dots

-zsh

> echo -e "Line 1\nLine 2\nLine 3" > file.txt
> sed -n '2p' file.txt


Line 2

p

p (print): Prints specific lines, much like a spotlight operator highlighting exactly what you want.

Example 4:

Dots

-zsh

> echo -e "One\nTwo\nThree" > numbers.txt
> sed -n '/Two/p' numbers.txt


Two

d

d (delete): Removes specified lines, imagine it like a paper shredder for specific parts of your text.

Example 5:

Dots

-zsh

> echo -e "Keep\nDelete\nKeep" > file.txt
> sed '/Delete/d' file.txt


Keep
Keep

s/p/r

s/pattern/replacement/ (substitute): Replaces text patterns, like find-and-replace in a word processor.

Example 6:

Dots

-zsh

> echo "The cat sleeps" > file.txt
> sed 's/cat/dog/' file.txt


The dog sleeps

a\

a\ (append): Adds new lines after matches.

Example 7:

Dots

-zsh

> echo "Original line" > file.txt
> sed '/Original/a\
New line below' file.txt


Original line
New line below

i\

i\ (insert): Adds new lines before matches.

Example 8:

Dots

-zsh

> echo "Original line" > file.txt
> sed '/Original/i\New line above' file.txt


New line above
Original line

>Quiz

Progress: Question ? out of ?

Question Title

Page written by Andrea Benvegnù