How To Use Sed To Replace String In File?

The sed command is an important command used to edit files or command outputs. The sed can be used to find and replace strings for a file easily via the command line interface. The sed name comes from the Stream Editor which provides advanced features to work with file contents. In this tutorial, we examine different examples to replace strings in string files.

Find and Replace String

The sed command works with the command provided to it. The following sed syntax can be used to find and replace strings in a file.

sed 's/OLD/NEW/g FILE
  • OLD is the old string that is searched for.
  • NEW is the new string that will be replaced with OLD.
  • FILE is the file name.

In the following example, we replace the string city with the citi for the file named db.txt

$ sed 's/city/citi/g' db.txt

Update File with Replaced String

By default, the replaced string is not updated in the file. The new content is displayed in the command line interface. But we can use the -i option in order to update the file content during replace operation.

$ sed -i 's/city/citi/g' db.txt

Replace Multiple Strings

We can replace multiple strings in a file by specifying the old and new strings as separate parameters. Each replacement statement is provided with the -e option to the sed command.

$ sed -e 's/city/citi/g' -e 's/ismail/ali/g' db.txt

Find and Replace First Occurrence

Sometimes we may need to find and replace only the first occurrence of the specified strings. We should remove the /g from the replacement statement below.

$ sed 's/city/citi' db.txt

Find and Replace Case Insensitive

By default, the sed command finds the string as case-sensitive. This means the city and CITY are not equal and do not match. We can make the find operation case insensitive adding the I after the /g .

$ sed 's/city/citi/gI' db.txt
See also  How To Check/Display Linux Kernel Version?

Leave a Comment