sed Scripting


sed Options

As with many command-line tools, sed has options available when you enter the command.

e

Yes, you can have more than 1 instruction with sed. This is just one way to do that.

sed -e 's/noon/3pm/' -e 's/fox/giraffe/' sedit.txt
The quick brown giraffe slept until 3pm

Another way is to separate each instruction with a semi-colon:

sed 's/noon/3pm/;s/fox/giraffe/' sedit.txt
The quick brown giraffe slept until 3pm

Or, for better clarity, you can put each instruction on a separate line:

sed '
s/noon/3pm/
s/fox/giraffe/
s/quick/slow/
' sedit.txt
The slow brown giraffe slept until 3pm

n

A note about n: as noted, the default action is to print every line. Using n, if you want to print a line, you must include a print command p following the last slash:

sed -n 's/noon/3pm/' sedit.txt
produces no output, while
sed -n 's/noon/3pm/p' sedit.txt
The quick brown fox slept until 3pm
does.

f

If you've progressed to the point of writing sed scripts, this is how to indicate that:

sed -f mySedScript.txt sedit.txt
The slow brown giraffe slept until 3pm

The script file mySedScript.txt contains

s/noon/3pm/
s/fox/giraffe/
s/quick/slow/

Before writing scripts, try to follow these points

  • Think through want you want to do before you do it
  • Explicitly describe a procedure to do it
  • Test, test, test before committing to the final script

    Recall that

    Have no fear.
    The cool thing about sed is that it DOES NOT alter the file, only the OUTPUT.

    so to save the changes to a file, you have to redirect to a new file.

    sed -f mySedScript.txt sedit.txt > NewSedit.txt