Commands.page Logo

How to Replace a Word in a File Using Ubuntu Terminal

This guide explains how to find and replace specific text within a file directly from the Ubuntu command line. You will learn to use the stream editor tool known as sed to perform search and replace operations efficiently without opening a graphical text editor.

Using the Sed Command

The most common way to replace text in Linux is using the sed command. The basic syntax for replacing a word is as follows:

sed -i 's/old_word/new_word/g' filename

In this command, -i edits the file in place, s stands for substitute, g ensures all occurrences on a line are replaced, and filename is the target file.

Creating a Backup Before Editing

It is highly recommended to create a backup before modifying files directly. You can modify the command to save a backup copy automatically:

sed -i.bak 's/old_word/new_word/g' filename

This creates a backup file named filename.bak before applying the changes to the original file.

Replacing Words in Multiple Files

You can apply the same replacement across multiple files using wildcards. For example, to replace a word in all text files within the current directory:

sed -i 's/old_word/new_word/g' *.txt

Use this carefully, as it will modify every matching file in the folder without further confirmation.

Verifying the Changes

After running the replacement command, verify the changes using grep to ensure the new word exists and the old word is removed:

grep "new_word" filename

This confirms that the operation was successful and the file contains the updated text.