DispersedNetUNIX Shell Programming

Lesson 2

How the sed Stream Editor Works

Objective: Describe sed’s processing cycle and its default output.

Sed reads input into a working buffer called pattern space. For the simple commands used here, that buffer contains one input line at a time. Sed applies the script’s instructions in order and normally prints the resulting pattern space before starting the next cycle. More advanced commands can collect multiple lines, but they are outside this module.

Three basic operations

InstructionEffect
dDiscard pattern space and start the next cycle.
pExplicitly print pattern space.
s/pattern/replacement/Replace the first matching occurrence in pattern space.
printf '%s\n' 'cat' 'dog' | sed 's/cat/feline/'

The output is feline followed by dog. With no file operand, sed reads standard input. The pipe supplies the two lines. The unchanged dog line still appears because automatic printing is enabled.



Default printing and -n

printf '%s\n' 'cat' 'dog' | sed -n '/cat/p'

The -n option suppresses automatic printing. The addressed p command explicitly prints only matching lines. Without -n, the cat line would be printed by p and then printed again automatically. The dog line would also be printed automatically. This explains the option rather than treating it as a mysterious requirement.

Saving results

A normal sed invocation writes output without changing the source. Redirect to a different, unused filename when you want to retain that output. Never redirect directly to the file being read: the shell can truncate it before sed opens it. In-place editing is a separate implementation-specific feature; it is incorrect to say that sed can never change a file.

A successful command can produce no visible change when its pattern matches nothing. Check the output as well as the exit status. For configuration changes, preserve backups and validate the resulting configuration before replacing an active file.