Easy Cheat Sheet for Using the sed Command

Using the sed command can help you do quick string manipulation in a shell script, which can be very handy. But knowing the exact parameters to do what you want may take some practice. Here are some tips that have helped me!

For all of these, the input text is “The quick brown fox jumps over the lazy dog on the sunny day”.

For replacing text, sed works as sed 's/<target>/<replacement>/' where s means “substitute”, and target is the text to replace with the replacement. The target is case sensitive.

Find and replace the first occurrence

This one is fairly straight forward, replacing the with a — sed 's/the/a/'

-> % echo 'The quick brown fox jumps over the lazy dog on the sunny day' | sed 's/the/a/'
The quick brown fox jumps over a lazy dog on the sunny day

Find and replace all

To replace all instances of “the”, include a g after the replacement text — sed 's/the/a/g'

-> % echo 'The quick brown fox jumps over the lazy dog on the sunny day' | sed 's/the/a/g'
The quick brown fox jumps over a lazy dog on a sunny day

Find and replace the last occurrence

To replace just the last occurrence of the target text, follow this pattern, utilizing a regex in the target — sed 's/\(.*\)the/\1all/'

-> % echo 'The quick brown fox jumps over the lazy dog on the sunny day' | sed 's/\(.*\)the/\1a/'
The quick brown fox jumps over the lazy dog on a sunny day

Find and remove target text

If you want to remove all instances of some target text, you can omit the replacement text, such as this to remove ” on the sunny day”

-> % echo 'The quick brown fox jumps over the lazy dog on the sunny day' | sed 's/ on the sunny day//'
The quick brown fox jumps over the lazy dog

Using sed on a file

You can feed a file as input to sed and have the output go to the terminal or piped to another file.

-> % echo 'The quick brown fox jumps over the lazy dog on the sunny day' > demo.txt && \
        sed 's/dog/cat/' demo.txt
The quick brown fox jumps over the lazy cat on the sunny day

Replacing within the file

If you want to replace text within the file, rather than dump the changes to the terminal, use the -i -r arguments.

-> % echo 'The quick brown fox jumps over the lazy dog on the sunny day' > demo.txt && \
        sed -i -r 's/dog/cat/' demo.txt

-> % cat demo.txt                  
The quick brown fox jumps over the lazy cat on the sunny day

Leave a Reply

Your email address will not be published. Required fields are marked *