Skip main navigation

Substitutions Using sed

Substitutions using sed
© Wellcome Genome Campus Advanced Courses and Scientific Conferences

Replacing one text string with another is something we often need to do.

This could be because we’ve discovered a repeated typo or misspelling in a file or because we’ve decided one piece of text needs replacing with something which reads better. We could, of course, do this manually, going through a file, correcting each appearance of an error. However, this is both time consuming and prone to human error. Linux thus includes a command called sed which allows us to make such substitutions automatically. The name sed is an abbreviation of stream editor.

The command is run in the following way:

sed 's/oldtext/newtext/' file.txt

This will replace the string oldtext with newtext, taking input from the file file.txt and by default write the result to standout output, which is your terminal. To replace writing to a new file use a redirect:

sed 's/oldtext/newtext/' file.txt > newfile.txt

This will output instead to a file called newfile.txt.

To make changes in place in the input file, use the -i option:

sed -i 's/oldtext/newtext/' file.txt

Only do this when absolutely sure that the substitution you are making is correct.

By default, sed will replace all instances of the old text string with the new text string.

© Wellcome Genome Campus Advanced Courses and Scientific Conferences
This article is from the free online

Bioinformatics for Biologists: An Introduction to Linux, Bash Scripting, and R

Created by
FutureLearn - Learning For Life

Our purpose is to transform access to education.

We offer a diverse selection of courses from leading universities and cultural institutions from around the world. These are delivered one step at a time, and are accessible on mobile, tablet and desktop, so you can fit learning around your life.

We believe learning should be an enjoyable, social experience, so our courses offer the opportunity to discuss what you’re learning with others as you go, helping you make fresh discoveries and form new ideas.
You can unlock new opportunities with unlimited access to hundreds of online short courses for a year by subscribing to our Unlimited package. Build your knowledge with top universities and organisations.

Learn more about how FutureLearn is transforming access to education