Terminal 101: Find and Replace Using Sed

Every Monday, we'll show you how to do something new and simple with Apple's built-in command line application.

Substitute All Occurrences of Word in a Single File

If you have a single file in which you wish to replace all occurrences of a single word with another, you can easily do it using the following command:

sed 's/FindThisWord/ReplaceWithThisWord/g' file.txt

Replace the word “FindThisWord” in the above command with the word you wish to be replaced, and substitute the word “ReplaceWithThisWord” in the above command with the word you wish to replace the word with.

This command will open sed, which will in turn print the text file to the screen, replacing the found word occurrences with the word you wish to use instead.

So, if we had the following document:

Apple is awesome!

We could run the following command to replace “Apple” in the above text document with “MacLife” instead:

sed 's/Apple/MacLife/g' sample.txt

The edited document will be printed to the screen for you to see.

Writing Changes to the File

All is good, but the above command doesn’t save the changes to the original file, it only prints the updated file to the screen. To write the changes back to an output file, you’ll use the following command instead:

sed -n 's/FindthisWord/ReplaceWithThisWord/gpw output.txt' file.txt

So, if we continue with the same example above, replacing “Apple” in the sentence with “MacLife,” then use the following command:

sed -n 's/Apple/MacLife/gpw output.txt' sample.txt

This will cause sed to not only change the file and print it to the screen, but will also cause the changes to be written back to a file called “output.txt” (you can change this name inside of the replacement string command.

Cory Bohon is a freelance technology writer, indie Mac and iOS developer, and amateur photographer. Follow this article's author on Twitter.